Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Simple Haskell question

Name: Anonymous 2011-07-12 15:24

Hi /prog/,

why bellow function doesn't produce an array of natural numbers from n to 0?

Prelude> let foo n = if n > 0 then n : (foo n-1) else []

Instead I got rather cryptic message:


Prelude> foo 5

<interactive>:1:0:
    No instance for (Num [t])
      arising from a use of `foo' at <interactive>:1:0-4
    Possible fix: add an instance declaration for (Num [t])
    In the expression: foo 5
    In the definition of `it': it = foo 5


How to fix this? Why this failsand bellow code works?

Prelude> 1 : 2 : []
[1,2]

Name: !!kCq+A64Losi56ze 2011-07-12 16:21

Okay, I'm not the Haskell master here, but don't you need to define a base case for n?

Name: Anonymous 2011-07-12 17:03

Function application has a higher operator precedence than -.

let foo n = if n > 0 then n : foo (n-1) else [] works.

Name: Anonymous 2011-07-12 20:53

>precedence

this is what Lisp-hating Haskellfags actually believe in

Name: Anonymous 2011-07-12 20:55

>>3
This. What that error message means is that a list (type [t]) is not a member of the Num typeclass, so you can't pass it to the - function.

Name: Anonymous 2011-07-12 20:58

>>4
let foo n = (if (n > 0) then ((n) : (foo (n - 1))) else ([]))
Is that better, ``faggot''?

Name: Anonymous 2011-07-12 21:11

>>6

(foo n) = (if (((>) n) 0) then (((:) n) (foo (((-) n) 1))) else [])

Oh, fuck that.
(define (foo n)
  (if (> n 0) (cons n (foo (- n 1)))
      '()))

Name: Anonymous 2011-07-12 21:14

(defun foo (n)
  (if (> n 0)
    (cons n (foo (- n 1)))
    nil))


expert cl programmer etc.

Name: Anonymous 2011-07-12 22:41

foo n = reverse (take n [1..])

Name: Anonymous 2011-07-12 22:44

>>9
U MENA ``foo n = [n,n-1..0]''.

Name: Anonymous 2011-07-12 22:58

(define (my anus)
  (my anus))

Name: Anonymous 2011-07-12 23:01

It is because the bellow function always succeeds.

Name: Anonymous 2011-07-13 0:31

Nomads? In my /prog/?

polecat kebabs

Name: Anonymous 2011-07-13 6:05

>>13
Eventually. He's a nomad after all.

Name: Anonymous 2011-07-13 6:33

NOMDAIC DNUS

Name: Anonymous 2011-07-13 11:15

>>5
This.

Fuck off forever.

Name: Anonymous 2011-07-13 11:22

>>16
Why should I care about the opinion of somebody who puts extra newlines after a quote?

Name: Anonymous 2011-07-13 11:58

>>16
fuck you faggot

Name: Anonymous 2011-07-13 19:31

>>17
Oh you little rebel you.

Don't change these.
Name: Email:
Entire Thread Thread List