2 ms·
Me too, of course. But every now and then you've got something a little strange to do, like slice a immutable list, and you're recursing. The thing about recur
by DanielBMarkham 17y ago
Me too, of course. But every now and then you've got something a little strange to do, like slice a immutable list, and you're recursing.
The thing about recursion is that for imperative guys, the first place they go is the for...next loop. Whereas in FP the first place you should go is the built-in stuff like map, fold, etc. But the second place is recursion (with the tail calls done correctly), not for..next
- nostrademons 17y agoSlicing an immutable list should be a library function (splitAt or span in Haskell), and even if it weren't, it can be written as a fold: splitAt :: Int -> [a] -> ([a], [a]) splitAt n xs = (reverse before, reverse after) where (before, after, _) = foldl' incr ([], [], 0) xs incr (ys, zs, m) x | m < n = (x:ys, zs, m + 1) incr (ys, zs, m) x = (ys, x:zs, m + 1) Basically, any imperative loop can be transformed into a foldl' where the accumulator is all the loop state and the increment function is the loop body, taking in the loop state and the current element. Breaks and continues are represented by returning the same loop state that is passed in. If you have breaks, you'll want a foldl (non-strict) instead of foldl' (strict), because lazy evaluation will prevent the rest of the loop from being executed.
- DanielBMarkham 17y agoThat works. Thanks for the tip -- I never thought of foldl as a universal replacement for for/next. Here's what I've been using for slicing: let slice l b e = let rec slice_2 l b e f = match l with [] -> f | h::t -> if (b<2) then if (e>0) then ( slice_2 t b (e-1) (f@[h]) ) else f else ( slice_2 t (b-1) (e-1) f ) in slice_2 l b e [];;
- eru 17y agoThough you are right that foldl and friends don't always help you. Especially in strict languages. But you can define your own combinators---to hide away the recursion in.