DEV Community

Discussion on: Write a script to find "Happy Numbers"

Collapse
 
heikodudzus profile image
Heiko Dudzus • Edited

And now that I have learned a simpler break condition for the problem, it is easier:

f :: Int -> Int
f = sum          -- Sum up the squares
  . map ((^2)    -- Compute squares
         .read   -- Convert digits to Ints
         .(:[])) -- Explode number string to list of digit strings
  . show         -- Convert input number to string

isHappy :: Int -> Bool
isHappy n | n == 4 = False
          | n == 1 = True
          | otherwise = isHappy (f n)

main = print $ filter isHappy [1..200]

On the other hand, I like the possibility of my original code to see the list of intermediate results to get a feeling for the problem.