Fix in Haskell
There’re many interesting features in Haskell, here I want to introduce and analyse the Fixed-point combinator, which spent me several hours understanding but only scratched the surface.
写于 2016 年,原文迁移,仅修正明显错字与失效链接。
目录
There’re many interesting features in Haskell, here I want to introduce and analyse the
Fixed-point combinator, which spent me several hours understanding but only scratched the surface.
Definition Of Fix
- You can find the definition of
Fixfunction in wiki. The definition is
fix :: (a -> a) -> a
fix f = let x = f x in xFix And Recursion
It seems a little confused. What does
let x = f x in xmean? For example,GNUisGNU is not Unix, so how could you expandGNU?GNU GNU GNU ... GNU is not Unix? Another example,let x = (1:) x in x, what will x like? A list of infinite 1. Still confused? You can trylet x = x + 2 in x, this will cause an exception because of stack overflow. The reason is that the(+2)operation is expanded constantly. So what isfixexactly?Fixcan be imported fromControl.Monad.Fix, its definition has been given above.Now we can learn the power of
Fixfrom an example. Thefactis used to calculatefactorial, here we calculate 5!. There are two kind of implements, the first is common recursion, like first line below. Instead, we can useFixto rewrite it. We pass a lambda function to fix as a parameter, the lambda function receivesrecandnas parameters,rechere is abstracted and it was initialized byif n == 0 then 1, this is indeed initialized for the lambda function, however you can think it as an anonymousrec.
Prelude> let fact n = if n == 0 then 1 else n * fact (n-1) in fact 5
120
Prelude> fix (\rec n -> if n == 0 then 1 else n * rec (n-1)) 5
120- In fact, from the definition of
Fix, we know thatfixmeans a fixed-point. What we need to do is to write the equation forfixlike below.Fixis used to find a fixed-point for given function.
f (fix f) = fix f- So why
fix (+2)is getting an exception? There is noxforx == x + 2, sofixcannot find an fixed-point for(+2). That’s whyfixfinally came into stack overflow. Now we are going to learn whatfixworks in details. We can expandfixlike below.
fix (2+)
= 2 + (fix (2+))
= 2 + (2 + fix (2+))
= 2 + (2 + (2 + fix (2+)))
= 2 + (2 + (2 + (2 + fix (2+))))
= ...
fix (1:)
= 1 : fix (1:)
= 1 : (1 : fix (1:))
= 1 : (1 : (1 : fix (1:)))- As you can see,
fix (1:)can work fine since the lazy evaluation of Haskell. If we passfix (1:)toshow,GHCIcan still work and output[1, 1, 1, .... Return to thefactexample now, how does it work? We write that lambda function passed tofixas a named functionfact'here, the definition isfact' rec n = if n == 0 then 1 else n * rec (n-1). Pass this tofix, fix will find a fixed-point offact', which is the functionfsuch thatf == fact' f. So we can writefact'like below.
f = fact' f
= \n -> if n == 0 then 1 else n * f (n-1)- Are you familiar with the equation above? The
fsubstituterecinfact', andfalso acts asfact' f, which is just recursion. So expandfixas we always did. (Codes below are copied from wiki)
fix fact'
= fact' (fix fact')
= (\rec n -> if n == 0 then 1 else n * rec (n-1)) (fix fact')
= \n -> if n == 0 then 1 else n * fix fact' (n-1)
= \n -> if n == 0 then 1 else n * fact' (fix fact') (n-1)
= \n -> if n == 0 then 1
else n * (\rec n' -> if n' == 0 then 1 else n' * rec (n'-1)) (fix fact') (n-1)
= \n -> if n == 0 then 1
else n * (if n-1 == 0 then 1 else (n-1) * fix fact' (n-2))
= \n -> if n == 0 then 1
else n * (if n-1 == 0 then 1
else (n-1) * (if n-2 == 0 then 1
else (n-2) * fix fact' (n-3)))
= ...Implementation Of Foldr & Reverse
- I am going to show some of the applications of
fix. First isreverse. We can writereverse'as the parameter offix. The type system ofreverse'is([a] ->[a]) -> ([a] -> [a]). Notice that I use a pair of parentheses out of[a] -> [a], that’s because curry.reverse'is just likefact', it receives a functionf, andfixis going to find afwhich satisfiesf = reverse' f. Now we can easily writereverse'below.
reverse' :: ([a] -> [a]) -> ([a] -> [a])
reverse' f [] = []
reverse' f (x:xs) = f xs ++ [x]
reverse = fix reverse'
-- expand the definition above
(fix reverse') [1,2,3]
= (reverse' (fix reverse')) [1,2,3]
= (reverse' f) [1,2,3]
= f [2,3] ++ [1]
= (reverse' f) [2,3] ++ [1]
= ...- Another example I am going to talk is
foldr. I found the kata aboutfixin Codewars, you can see it here. I didn’t pass the time limitation, and finally I got clues from conversations. There are several ways to writefoldrbyfix, however, you need to maintain the feature offoldr, the lazy evaluation. I will show two of them both satisfying the lazy evaluation.
foldr' :: ((a ->b ->b) ->b ->[a] ->b) ->((a ->b ->b) ->b ->[a] ->b)
foldr' f g acc [] = acc
foldr' f g acc (x:xs) = f g (g x acc) xs
foldr' :: ((a ->b ->b) ->b ->[a] ->b) ->((a ->b-> b) ->b ->[a] ->b)
foldr' f g acc [] = acc
foldr' f g acc (x:xs) = g x (f g acc xs)
foldr = fix foldr'- Which is better? In my own opinion, the first is better since it is written in a format of tail-end recursion. This would not expand the stack space it used. However, the second needs to expand until the end of the list. But, after my experiment testing big integers, both of them met stack overflow at the same size while works as same as each other when they can deal with the parameters. This proved that my thought was wrong. So, why the two formats have same performance? Stay for thought.
I hope this article could give you some help. If this article has any error, or you have some problems/suggestions, please e-mail me. I am glad to learn from each other.