Seems a function should have a name to be recursive(in order to call itself), so how does a lambda function be recursive?
I searched wikipedia and it says this could be done by a "Y-combinator". I don't have much math theory backgroup, it just tell me that "Y-combinator" is discovered by Haskell himself. Called "fix" keyword in Haskell language, I tried:
Prelude> let fact = fix (\f n -> if n == 0 then 1 else n * (f (n-1)))
<interactive>:17:12: Not in scope: ‘fix’
Seems failed, but how to use "fix" keyword to do what I expected?
fixis defined as:so it expands into
f (f (f (f ...)))i.e. an infinite sequence of nested applications of the input functionfto some parameterx.You can give your lambda function a top-level definition e.g.
or equivalently:
you can provide this function to
fixto obtain a function(Int -> Int)i.e.if you expand this definition you get
due to laziness, the repeated applications of
factFare only evaluated ifn /= 0so the above function applied to0will evaluate immediately to 1.You can see in this expansion that
factFis being provided as an argument to itself which it then applies to smaller version ofn. SincefactNis the same as your lambda function, the same thing is happening there - the parameterfinside the lambda is the lambda itself which it can then call recursively.