-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeadfish.hs
59 lines (40 loc) · 1.25 KB
/
deadfish.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
{-
Write a simple parser that will parse and run Deadfish.
Deadfish has 4 commands, each 1 character long:
i increments the value (initially 0)
d decrements the value
s squares the value
o outputs the value into the return array
Invalid characters should be ignored.
parse "iiisdoso" -> [ 8, 64 ]
-}
module Kata.Deadfish (parse) where
import Test.Hspec ( hspec, it, shouldBe, SpecWith )
data Command = Increment | Decrement | Square | Output | Noop
command :: Command -> (Int, [Int]) -> (Int, [Int])
command Increment (n, arr) = (n + 1, arr)
command Decrement (n, arr) = (n - 1, arr)
command Square (n, arr) = (n^2, arr)
command Output (n, arr) = (n, n:arr)
command Noop x = x
commandFor :: Char -> Command
commandFor 'i' = Increment
commandFor 'd' = Decrement
commandFor 's' = Square
commandFor 'o' = Output
commandFor _ = Noop
parse :: String -> [Int]
parse s = reverse result where
commands = map commandFor s
(n, result) = foldl (flip command) (0, []) commands
-- testing
spec :: SpecWith ()
spec = do
it "Example test" $ do
parse "iiisdoso" `shouldBe` [ 8, 64 ]
it "Francisco test" $ do
parse "francisco" `shouldBe` [1]
it "Fun test" $ do
parse "oioiosodosodo" `shouldBe` [0,1,2,4,3,9,8]
main :: IO ()
main = hspec spec