Search code examples
haskellincrement

How do I increase a number over and over again in Haskell?


I want to increase a number for every new call so instead of bonbons(x-10) should be bonbons(x-20), bonbons(x-30) and so on.

module AufgabeBonbons where

bonbons :: Int -> Int
bonbons x | x <= 550 && x >= 10 = 1 + bonbons(x-10)
            |otherwise = 0

I tried to create a new function but I am not so sure if this is the right way to handle this problem.


Solution

  • Based on the following description:

    Okay so I have an amount of cents x and I want to buy candy. The candy each cost 10 cents, 20 cents and so on up to 1 euro. I can only buy one candy of each kind (each centkind) and I want to know how mandy candies I can buy.

    You are essentially looking for the largest n for which the equation holds:

    enter image description here

    This is a known series that can be solved as:

    enter image description here

    or this:

    enter image description here

    Indeed, image that we have 30 cents, then the result is (√5×√125-5)/10=2.

    We thus can implement this as:

    bonbons :: Int -> Int
    bonbons x = min 10 (floor ((sqrt (5 * (4*x'+5)) - 5) / 10))
      where x' = fromIntegral x
    

    I want to increase a number for every new call so instead of bonbons(x-10), should be bonbons(x-20), bonbons(x-30) and so on.

    We can work with a variable that specifies the amount for the next bonbon:

    bonbons :: Int -> Int
    bonbons = go 10
      where go m n
               | m <= n && m < 100 = 1 + go (m+10) (n-m)
               | otherwise = 0