-
SequencesArraysData Types
Code module Collatz where collatz :: Int -> [Int] collatz = iterate next where next n | even n = n `div` 2 | odd n = n * 3 + 1
Test Cases import Test.Hspec import Collatz main = hspec $ do describe "Collatz sequence" $ do it "One" $ do (take 5 $ collatz 1) `shouldBe` [1,4,2,1,4] it "Zero" $ do (take 3 $ collatz 0) `shouldBe` [0,0,0] it "Even" $ do (take 3 $ collatz 68) `shouldBe` [68,34,17] it "Odd" $ do (take 3 $ collatz 23) `shouldBe` [23,70,35] it "Cycle" $ do (take 6 $ collatz (-5)) `shouldBe` [-5,-14,-7,-20,-10,-5] it "Long" $ do (take 19 $ collatz 28) `shouldBe` [28,14,7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1]
Output:
-
Code - module Collatz where
- collatz :: Int -> [Int]
collatz n = n : collatz nextwhere next | even n = n `div` 2| odd n = n * 3 + 1- collatz = iterate next
- where next n | even n = n `div` 2
- | odd n = n * 3 + 1
- All
- {{group.name}} ({{group.count}})
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}