is the fix function a better way to replace while loops?

Viewed 84

When you are in a do block, in order to emulate a "while loop" it's common to see people declaring a "loop" function in a let statement. however, there is this clever function "fix" which allows you to declare and use the function at the same time

main = do
   let fac n r = if n == 1 then r else fact (n-1) (n*r)
   print $ fact 4 1 -- 24
   
   print $ fix (\rec n r -> if n == 1 then r else rec (n-1) (n*r)) 4 1

the question is, does fix have any advantage over using a let statement? is slower or uses more memory?

1 Answers

No, there is no advantage. It's even implemented as a let expression:

fix f = let x = f x in x
Related