Search code examples
haskellhugs

Can someone explain to me the following Haskell expression


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


Solution

  • : 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.