DEV Community

loading...

Discussion on: Daily Challenge #271 - Simulate Population Growth

Collapse
cipharius profile image
Valts Liepiņš • Edited

Lazy Haskell goodness:

import Data.Maybe (fromMaybe)
import Data.List (findIndex)

nbYear :: Int -> Double -> Int -> Int -> Int
nbYear p0 growth aug pGoal = fromMaybe 0 $ maybeYears
  where
    maybeYears = findIndex (>= pGoal) $ p0 : nbYear' p0
    nbYear' p =
      let p' = (ceiling $ fromIntegral p * (1 + growth')) + aug
      in p' : nbYear' p'
    growth' = growth / 100

General idea of the solution is to generate an infinite list of population growth per year with the recursive function nbYear'. Since Haskell is lazy, I can then use this infinite list to find the first item in the list, which exceeds the goal population.