Merge pull request #358 from bjh21/bjh21-extra-tests
[jackhill/mal.git] / elm / Utils.elm
CommitLineData
0d8a8d94
JB
1module Utils
2 exposing
3 ( decodeString
4 , encodeString
5 , makeCall
6 , wrap
7 , maybeToList
4e84165f 8 , zip
c792f15e 9 , last
86fcd61d 10 , justValues
0d8a8d94
JB
11 )
12
13import Regex exposing (replace, regex, HowMany(All))
14import Types exposing (MalExpr(..))
15
16
17decodeString : String -> String
18decodeString =
19 let
20 unescape { match } =
21 case match of
22 "\\n" ->
23 "\n"
24
25 "\\\"" ->
26 "\""
27
28 "\\\\" ->
29 "\\"
30
31 other ->
32 other
33 in
34 String.slice 1 -1
35 >> replace All (regex "\\\\[\\\"\\\\n]") unescape
36
37
38encodeString : String -> String
39encodeString =
40 let
41 escape { match } =
42 case match of
43 "\n" ->
44 "\\n"
45
46 "\"" ->
47 "\\\""
48
49 "\\" ->
50 "\\\\"
51
52 other ->
53 other
54 in
55 wrap "\"" "\""
56 << replace All (regex "[\\n\\\"\\\\]") escape
57
58
59makeCall : String -> List MalExpr -> MalExpr
60makeCall symbol args =
61 MalList <| (MalSymbol symbol) :: args
62
63
64wrap : String -> String -> String -> String
65wrap prefix suffix str =
66 prefix ++ str ++ suffix
67
68
69maybeToList : Maybe a -> List a
70maybeToList m =
71 case m of
72 Just x ->
73 [ x ]
74
75 Nothing ->
76 []
4e84165f
JB
77
78
79zip : List a -> List b -> List ( a, b )
80zip a b =
81 case ( a, b ) of
82 ( [], _ ) ->
83 []
84
85 ( _, [] ) ->
86 []
87
88 ( x :: xs, y :: ys ) ->
89 ( x, y ) :: zip xs ys
c792f15e
JB
90
91
92last : List a -> Maybe a
93last list =
94 case list of
95 [] ->
96 Nothing
97
98 [ x ] ->
99 Just x
100
101 x :: xs ->
102 last xs
86fcd61d
JB
103
104
105justValues : List (Maybe a) -> List a
106justValues list =
107 case list of
108 [] ->
109 []
110
111 (Just x) :: rest ->
112 x :: (justValues rest)
113
114 Nothing :: rest ->
115 justValues rest