Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional non recursive approach to looping in Haskell

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?

like image 628
Atmaram Shetye Avatar asked Dec 27 '22 01:12

Atmaram Shetye


1 Answers

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.

like image 99
Daniel Gratzer Avatar answered Jan 22 '23 20:01

Daniel Gratzer