File tree Expand file tree Collapse file tree 3 files changed +45
-0
lines changed
Expand file tree Collapse file tree 3 files changed +45
-0
lines changed Original file line number Diff line number Diff line change 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)
Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments