2

Is there anyway I could check the number of recursion the program is at. For example, I want to stop the recursion after 2 times. Is there anyway to do that in haskell.

2
  • 3
    Check writer monad at learnyouahaskell.com/for-a-few-monads-more#writer Commented Aug 7, 2018 at 3:46
  • this sounds a bit like you're looking for for-loops in haskell - could you explain what you need the recursion for? Commented Aug 7, 2018 at 11:56

1 Answer 1

6

Yes, there is but...

Stopping recursion is normally done when some final state is achieved, something like "I've run out of data to process" or "I have reached the base case." When I see something as arbitrary as "after 2 times" I want to ask where you came up with 2.

However in the interest of answering the question asked:

You need to pass in a counter to the recursive function and bail out when you have done the required number of cycles. For cases like this where the number of cycles is not a matter external to the function, it is typically the case that one creates an auxilary function to introduce it.

myFunction :: Value -> Value
myFunction init = recurse 2 init
 where
   recurse :: Int -> Value -> Value
   recurse 0 result = result
   recurse n intermediate = recurse (n-1) (someFun intermediate)
Sign up to request clarification or add additional context in comments.

2 Comments

The tuple here is a bit odd, rather than simply taking 2 arguments.
amolloy, yes in looking at it, I think you're right. I had Writer Monad in mind when I was writing this, but decided that was more information than was needed and never took the tuple back out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.