Skip to content

Instantly share code, notes, and snippets.

@Kornel
Last active August 29, 2015 14:20
Show Gist options
  • Save Kornel/8be95718774f88eb45d1 to your computer and use it in GitHub Desktop.
Save Kornel/8be95718774f88eb45d1 to your computer and use it in GitHub Desktop.
module Collatz where
collatz :: (Integral a) => a -> [a]
collatz a = takeWhileIncl (/= 1) $ collatzSeq a
nextCollatz :: (Integral a) => a -> a
nextCollatz n = if (even n) then n `div` 2 else (3 * n + 1)
collatzSeq :: (Integral a) => a -> [a]
collatzSeq = iterate nextCollatz
takeWhileIncl :: (a -> Bool) -> [a] -> [a]
takeWhileIncl _ [] = []
takeWhileIncl p xs = left ++ [head right]
where (left, right) = span p xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment