You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We can perform case analysis for `Json` values using the `foldJson` function.
97
+
We can perform case analysis for `Json` values using the `caseJson` function.
117
98
This function is necessary because `Json` is not an algebraic data type. If
118
99
`Json` were an algebraic data type, we would not have as much need for this
119
100
function, because we could perform pattern matching with a `case ... of`
120
101
expression instead.
121
102
122
-
The type of `foldJson` is:
103
+
The type of `caseJson` is:
123
104
124
105
```purescript
125
-
foldJson :: forall a.
126
-
(JNull -> a) -> (JBoolean -> a) -> (JNumber -> a) ->
127
-
(JString -> a) -> (JArray -> a) -> (JObject -> a) ->
128
-
Json -> a
106
+
caseJson
107
+
:: forall a
108
+
. (Unit -> a)
109
+
-> (Boolean -> a)
110
+
-> (Number -> a)
111
+
-> (String -> a)
112
+
-> (Array Json -> a)
113
+
-> (Object Json -> a)
114
+
-> Json
115
+
-> a
129
116
```
130
117
131
-
That is, `foldJson` takes six functions, which all must return values of some
132
-
particular type `a`, together with one `Json` value. `foldJson` itself also
118
+
That is, `caseJson` takes six functions, which all must return values of some
119
+
particular type `a`, together with one `Json` value. `caseJson` itself also
133
120
returns a value of the same type `a`.
134
121
135
-
A use of `foldJson` is very similar to a `case ... of` expression, as it allows
136
-
you to handle each of the six possibilities for the `Json` value you passed in.
137
-
Thinking of it this way, each of the six function arguments is like one of the
138
-
case alternatives. Just like in a `case ... of` expression, the final value
122
+
A use of `caseJson` is very similar to a `case ... of` expression, as it allows
123
+
you to handle each of the six possibilities for the `Json` value you passed in. Thinking of it this way, each of the six function arguments is like one of the
124
+
case alternatives.
125
+
126
+
The function that takes `Unit` as an argument is for matching `null` values. As there is only one possible `null` value, we use the PureScript `Unit` type, as correspondingly there is only one possible `Unit` value.
127
+
128
+
Just like in a `case ... of` expression, the final value
139
129
that the whole expression evaluates to comes from evaluating exactly one of the
140
130
'alternatives' (functions) that you pass in. In fact, you can tell that this
141
-
is the case just by looking at the type signature of `foldJson`, because of a
131
+
is the case just by looking at the type signature of `caseJson`, because of a
142
132
property called *parametricity* (although a deeper explanation of parametricity
0 commit comments