Skip to content

Instantly share code, notes, and snippets.

@jdewind
Created December 5, 2012 03:44
Show Gist options
  • Save jdewind/4212017 to your computer and use it in GitHub Desktop.
Save jdewind/4212017 to your computer and use it in GitHub Desktop.
Ruby vs Haskell: Collatz Sequence
-- Collatz Sequence (http://en.wikipedia.org/wiki/Collatz_conjecture)
chain :: (Integral a) => a -> [a]
chain 0 = error "Zero will recurse forever"
chain 1 = [1]
chain x
| even x = x:chain (x `div` 2)
| odd x = x:chain (x*3 + 1)
def chain(num)
raise "Zero is invalid" if num == 0
return [1] if num == 1
results = []
if num.even?
results << chain(num / 2).insert(0, num)
else
results << chain(num*3 + 1).insert(0, num)
end
results.flatten
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment