-
Notifications
You must be signed in to change notification settings - Fork 0
/
RleParser.elm
102 lines (77 loc) · 2.18 KB
/
RleParser.elm
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
module RleParser exposing (parse)
import Parser exposing (..)
type alias GridState =
{ x : Int
, y : Int
, cellList : List ( Int, Int )
}
type CellState
= Alive
| Dead
| EmptyLine
init =
{ x = 0
, y = 0
, cellList = []
}
parse : String -> Result (List DeadEnd) (List ( Int, Int ))
parse =
run cells
cells : Parser (List ( Int, Int ))
cells =
loop init cellHelp
cellHelp : GridState -> Parser (Step GridState (List ( Int, Int )))
cellHelp gridState =
oneOf
[ succeed (addCells gridState)
|= int
|= cellToken
, succeed (addCells gridState 1)
|= cellToken
, succeed (nextLine gridState 1)
|. token "$"
, succeed (Done gridState.cellList)
|. token "!"
, succeed (Done gridState.cellList)
|. end
, problem "Invalid RLE string. I support only two states, so use `b` and `o` for cells"
]
cellToken : Parser CellState
cellToken =
oneOf
[ map (\_ -> Dead) (token "b")
, map (\_ -> Alive) (token "o")
, map (\_ -> EmptyLine) (token "$")
]
addCells : GridState -> Int -> CellState -> Step GridState (List ( Int, Int ))
addCells gridState count aliveOrDead =
case aliveOrDead of
Alive ->
let
newX =
gridState.x + count
xRange =
List.range gridState.x (newX - 1)
cellsToAdd =
List.map (\i -> ( i, gridState.y )) xRange
updatedState =
{ gridState | x = newX, cellList = gridState.cellList ++ cellsToAdd }
in
Loop updatedState
Dead ->
let
newX =
gridState.x + count
updatedState =
{ gridState | x = newX }
in
Loop updatedState
EmptyLine ->
nextLine gridState count
nextLine : GridState -> Int -> Step GridState (List ( Int, Int ))
nextLine gridState count =
let
updatedState =
{ gridState | x = 0, y = gridState.y + count }
in
Loop updatedState