9
f :: Integer -> Integer -> [Integer]
f i n = n : f (i+2) (n+i)

can someone explain to me what it does. i know it returns [0,1,4,9,16..] but i dont understand how and what n : f means

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
124697
  • 22,097
  • 68
  • 188
  • 315

2 Answers2

10

: is the "cons" operator and constructs a new list whose head is the value to the left of the operator and whose tail is the value to the right of the operator. Thus 0 : [1, 2, 3] is the list [0, 1, 2, 3].

Check the behaviour of this function, by evaluating f 1 0 as follows:

f 1 0 = 0 : f 3 1

i.e. f 1 0 is the result of creating a new list consisting of 0 at the head and the list returned by f 3 1 as its tail. Similarly, f 3 1 is as follows:

f 3 1 = 1 : f 5 4

i.e. f 3 1 is the result of creating a new list consisting of 1 at the head and the list returned by f 5 4 as its tail.

Thus, the function recursively builds up a list. Furthermore, it is infinitely tail-recursive (since it has no terminating condition) and will thus result in an infinitely long list.

As for the initial line, f :: Integer -> Integer -> [Integer], this indicates that f is a function that takes two integers (Integer -> Integer) and returns a list of integers ([Integer]). Strictly speaking, f takes an integer (Integer) and returns another function that takes an integer and returns a list of integers (Integer -> [Integer]) as a resulting of function currying. This is a concept you will become familiar with as you get into Haskell and other functional programming languages in greater depth.

Richard Cook
  • 32,523
  • 5
  • 46
  • 71
5

The code in your question does nothing because it contains a type error and a syntax error.

f :: Integer -> Integer --> [Integer]

As you can see from the highlighting the last bit is a comment because -- starts a comment in Haskell. As a consequence, the declared type of f is Integer -> Integer, which is wrong. To fix this change --> to ->.

f i n = n : f (i+2) (n+i]

Here you have an opening ( and then a closing ]. Obviously that's wrong. To fix this change (n+i] to (n+i).

Now that that that's done, here's what the fixed code does:

: is a constructor for the list type. x : xs is the list which has x as its head and xs as its tail. n : f (i+2) (n+i) gets parsed as n : (f (i+2) (n+i)) (not (n : f) (i+2) (n+1) as you seem to believe). So it creates a list whose head is n and its tail is the result of f (i+2) (n+1).

sepp2k
  • 363,768
  • 54
  • 674
  • 675