I recently learned about Data.Function.fix
, and now I want to apply it everywhere. For example, whenever I see a recursive function I want to "fix
" it. So basically my question is where and when should I use it.
To make it more specific:
1) Suppose I have the following code for factorization of n
:
f n = f' n primes
where
f' n (p:ps) = ...
-- if p^2<=n: returns (p,k):f' (n `div` p^k) ps for k = maximum power of p in n
-- if n<=1: returns []
-- otherwise: returns [(n,1)]
If I rewrite it in terms of fix
, will I gain something? Lose something? Is it possible, that by rewriting an explicit recursion into fix
-version I will resolve or vice versa create a stack overflow?
2) When dealing with lists, there are several solutions: recursion/fix, foldr/foldl/foldl', and probably something else. Is there any general guide/advice on when to use each? For example, would you rewrite the above code using foldr
over the infinite list of primes?
There are, probably, other important questions not covered here. Any additional comments related to the usage of fix
are welcome as well.
foldr
andfoldl'
if you can,fix
or explicit recursion if you must. The latter are less powerful so the reader of your code can deduce more properties from it. – Asquith_Y f = f (_Y f)
(recursion, value--copying) andfix f = x where x = f x
(corecursion, reference--sharing). – Pl