1

How can I limit this recursion function, so it will just stop recalling after maximum 23 times? However, I wouldn't like to modify the definition of the function binf.

binf :: Double -> [Int]
binf 0 = []
binf x =
  [fromIntegral(truncate x)] ++
  binf(x*2-fromIntegral(truncate x*2))
5
  • You add an extra parameter: the recursion depth. But the question is more: "what do you want to return in that case"? Commented Oct 18, 2018 at 10:05
  • Do I understand correctly that you don't want to modify the type of binf (Double -> [Int]) but can modify the content of it? If yes, you can add an enclosed function that takes the depth as additional parameter and thus hide that away from the caller Commented Oct 18, 2018 at 10:06
  • 2
    Here however you can use take 23 (binf some_x), since due to Haskell's laziness, you will then stop calling the binf. Commented Oct 18, 2018 at 10:06
  • Thank you, take 23 worked perfectly! Commented Oct 18, 2018 at 10:23
  • The second case can be simplified: binf x = truncate x : binf (x*2 - fromIntegral (truncate x*2)). Commented Oct 18, 2018 at 15:23

1 Answer 1

2

In General
You can wrap the recursion within an inner function. For example this function returns a list of descending numbers, starting with the input number x.

binf :: Int -> [Int]
binf x = go x 23
    where
        go :: Int -> Int -> [Int]
        go 0 _ = []
        go _ 0 = []
        go y rec = [y] ++ (go (y-1) (rec-1))

Here, rec is a recursion counter and the recursion ends when it reaches 0 or when the recursion ended naturally by the input being 0.
If you run binf 50, you will get a result [50, 49, ... , 28], which has a length of 23 - the number specified as initial rec.

In your case
Since your recursion is just appending to a list, and haskell features lazy evaluation, you can solve this differently:

Here however you can use take 23 (binf some_x), since due to Haskell's laziness, you will then stop calling the binf.
- Willem Van Onsem (comment link)

Sign up to request clarification or add additional context in comments.

Comments

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.