Skip to content

Instantly share code, notes, and snippets.

@esoergel
Created June 26, 2014 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esoergel/b017a9aa632e9433a2af to your computer and use it in GitHub Desktop.
Save esoergel/b017a9aa632e9433a2af to your computer and use it in GitHub Desktop.
Collatz Conjecture in Haskell
collatzNaive :: Int -> [Int]
collatzNaive 1 = [1]
collatzNaive n = n:sequence
where sequence
| even n = collatzNaive (n `div` 2)
| otherwise = collatzNaive (n*3 + 1)
-- Store things as a linked list of tuples - [(1, 1), (2, 2), (3, 8), (4, 3)...]
addKV :: (Integral a) => [(a, a)] -> a -> a -> [(a, a)]
addKV [] k v = [(k, v)]
addKV (pair:t) k v
| k0 == k = (k, v):t
| k0 > k = (k, v):pair:t
| otherwise = pair:(addKV t k v)
where (k0, v0) = pair
getValue :: (Integral a) => [(a, a)] -> a -> Maybe a
getValue dict k =
let match = find (\(k0, v0) -> k0 == k) dict
in case match of
Just (k, v) -> Just v
Nothing -> Nothing
collatz dict n = case getValue dict n of
Just v -> (dict, v)
Nothing -> if n == 1 then (dict, 1) else (newDict val)
where nextNum | even n = (n `div` 2)
| otherwise = (n*3 + 1)
(d, v) = collatz dict nextNum
{- let (d, val) | even n = collatz dict (n `div` 2) -}
{- | otherwise = collatz dict (n*3 + 1) -}
{- newDict = addKV d n val -}
{- in (newDict, val) -}
@esoergel
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment