I am a bit confused. There is no problem with defining ordinary recursive functions in Haskell. At the same time there is the standard fix
function for defining recursive lambdas via fixed points. But besides being less readable a recursive lambda defined like that has an application overhead compared to a regular recursive functions that call themselves directly. So where would I practically need recursive lambdas and fix
?
Asked
Active
Viewed 154 times
3
![](../../users/profiles/2751851.webp)
duplode
- 31,361
- 7
- 69
- 130
![](../../users/profiles/139667.webp)
Trident D'Gao
- 15,993
- 14
- 77
- 141
1 Answers
8
You never need it. Sometimes it's mildly convenient, though.
foo = do
foo1
x <- foo2
let loop = do
y <- bar x
if pred y then loop else return y
z <- loop
foo3 z
vs
foo = do
foo1
x <- foo2
z <- fix $ \loop -> do
y <- bar x
if pred y then loop else return y
foo3 z
I find the second to bit a bit less cumbersome. It's a minor thing, but I think it makes weird (ie, more complicated than that example, less likely to be something that exists in a library already) monadic looping look enough better that it's worth it to me to use that idiom. I also do like that it avoids binding another name into the context of the do
block.
![](../../users/profiles/383200.webp)
Carl
- 24,118
- 4
- 57
- 79