I use Haskell for my programming during leisure these days. Being a programmer in imperative languages for over 8 years, it is tough to wrap my head around some functional constructs (especially the folds). I was solving a problem from project Euler, and happened to produce the following code.
f (num, den) s | num*10 < den = s
| otherwise = f (ratio (num, den) s') s'
where s' = (s+2)
Can this explicit recursion be rewritten using folds or some other functional construct? The main hurdle for me in using a fold was to come up with the step function. Eventually I gave up, and resorted to the recursion.
EDIT: Also, how do I make the output returned by another function within a function as the input to the calling function without explicit recursion?
There's always good old until
f = until test func
where test ((a, b), _) = a * 10 < b
func (p, s) = (ratio p s+2, s+2)
To be fair though, you're really always going to have some kind of recursion, it's just a matter of how much you abstract it away. There is no "loop" in Haskell.
As to your second question, I believe you've just asked "How do I have a function call itself without doing recursion". In short, you can't since that's the definition of recursion.
However with higher order functions like until
iterate
and fix
(Look at the implementation of that one) you can avoid ever having to call your worker function. They take care of doing the explicit recursion under the covers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With