Functional non-recursive approach to cyclization in Haskell

I use Haskell for my leisure programming these days. Being a programmer in imperative languages ​​for more than 8 years, it is difficult to wrap your head around some functional constructions (especially folds). I solved the problem from the Euler project and got 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 obstacle for me in using the crease was the creation of the step function. In the end, I gave up and resorted to recursion.

EDIT: How can I draw the output returned by another function inside the function as input to the calling function without explicit recursion?

+4
source share
1 answer

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, you really will always have some kind of recursion, it's just a matter of how distracting you are. Haskell has no "loop".

As for your second question, I believe that you just asked: "How do I call a function call without doing a recursion." In short, since then you cannot define recursion.

However, with higher order functions such as until iterate and fix (look at the implementation of this), you can avoid having to name your working function. They take care of explicit recursion under the covers.

+10
source

Source: https://habr.com/ru/post/1486503/


All Articles