Skip to content

Instantly share code, notes, and snippets.

@puffnfresh
Created October 13, 2011 05:43
Show Gist options
  • Save puffnfresh/1283487 to your computer and use it in GitHub Desktop.
Save puffnfresh/1283487 to your computer and use it in GitHub Desktop.
Haskell State Monad solution to https://github.com/tonymorris/happy-numbers
module Happy where
import Control.Monad
import Control.Monad.State -- Brian
happy ::
Int
-> Bool
happy =
-- Start of Brian's code
(\n -> evalState (happy' n) [])
happy' n = do
state <- get
let answer = sum $ map (^ 2) $ toDigits n
if answer == 1
then return True
else if answer `elem` state
then return False
else do
put $ answer:state
happy' answer
toDigits = (map (readDigit . (:[]))) . show
readDigit :: String -> Int
readDigit = read
-- End of Brian's code
main ::
IO ()
main =
let happys = [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100, 103, 109, 129, 130, 133, 139, 167, 176, 188, 190, 192, 193, 203, 208, 219, 226, 230, 236, 239, 262, 263, 280, 291, 293, 301, 302, 310, 313, 319, 320, 326, 329, 331, 338, 356, 362, 365, 367, 368, 376, 379, 383, 386, 391, 392, 397, 404, 409, 440, 446, 464, 469, 478, 487, 490, 496]
in mapM_ (\(i, p) -> let passes = p == (i `elem` happys)
in unless passes $ putStrLn ("happy fails for: " ++ show i)) $ map (\n -> (n, happy n)) [1..500]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment