Created
June 26, 2014 17:15
-
-
Save esoergel/b017a9aa632e9433a2af to your computer and use it in GitHub Desktop.
Collatz Conjecture in Haskell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) -} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://projecteuler.net/problem=14