banovski

Collatz

Jan 27th, 2022 (edited)
1,001
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ifOne :: Integral a => [a] -> [a]
  2. ifOne xs =
  3.   if lst == 1
  4.     then xs
  5.     else oddOrEven xs
  6.   where
  7.     lst = last xs
  8.  
  9. oddOrEven :: Integral a => [a] -> [a]
  10. oddOrEven xs =
  11.   if even lst
  12.     then ifOne (xs ++ [div lst 2])
  13.     else ifOne (xs ++ [lst * 3 + 1])
  14.   where
  15.     lst = last xs
  16.  
  17. collatz :: Integral a => a -> [a]
  18. collatz x =
  19.   if x < 1
  20.     then error "An integer greater than zero is required!"
  21.     else ifOne [x]
  22.  
  23. main = print $ collatz 104
  24.  
  25. -- [104,52,26,13,40,20,10,5,16,8,4,2,1]
  26.  
Add Comment
Please, Sign In to add comment