Skip to content

Commit bbffb0b

Browse files
committed
Solve 'Can you get the loop ?' kata (#10)
1 parent 5c01a57 commit bbffb0b

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

src/CanYouGetTheLoop.hs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
module CanYouGetTheLoop (loopSize) where
2+
3+
import CanYouGetTheLoop.Types
4+
5+
-- https://www.codewars.com/kata/52a89c2ea8ddc5547a000863/train/haskell
6+
7+
loopSize :: (Eq a) => Node a -> Int
8+
loopSize = length . findLoop
9+
10+
findLoop :: (Eq a) => Node a -> [Node a]
11+
findLoop node = go [] . detectLoop node . next $ node
12+
where
13+
detectLoop :: (Eq a) => Node a -> Node a -> Node a
14+
detectLoop slow fast
15+
| slow == fast = slow
16+
| otherwise = detectLoop (next slow) (next (next fast))
17+
18+
go :: (Eq a) => [Node a] -> Node a -> [Node a]
19+
go [] node = go [node] (next node)
20+
go found node
21+
| node `elem` found = found
22+
| otherwise = go (found ++ [node]) (next node)

src/CanYouGetTheLoop/Types.hs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
module CanYouGetTheLoop.Types (Node (..), next) where
2+
3+
data Node a = Node a (Node a)
4+
5+
instance (Eq a) => Eq (Node a) where
6+
(Node x _) == (Node y _) = x == y
7+
8+
next :: Node a -> Node a
9+
next (Node x node) = node

test/CanYouGetTheLoopSpec.hs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
module CanYouGetTheLoopSpec (spec, main) where
2+
import CanYouGetTheLoop.Types
3+
import CanYouGetTheLoop
4+
import Test.Hspec
5+
6+
main = hspec spec
7+
spec = do
8+
describe "loopChain" $ do
9+
it "finds loop in list of 4 nodes" $ do
10+
let node1 = Node 1 node2
11+
node2 = Node 2 node3
12+
node3 = Node 3 node4
13+
node4 = Node 4 node2
14+
loopSize node1 `shouldBe` 3

0 commit comments

Comments
 (0)