简体   繁体   中英

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

: 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

ie 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

ie 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.

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM