Skip to content

Commit 496f375

Browse files
authored
feat(decode): add indirect combinator to help with recursion (#6)
1 parent 8a4fc3a commit 496f375

File tree

4 files changed

+17
-0
lines changed

4 files changed

+17
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,9 @@ Please see [LICENSE.LGPL-3.0](https://github.com/glennsl/rescript-json-combinato
117117

118118
## Changes
119119

120+
### 1.3.0
121+
- add `Decode.indirect` to help with decoding recursive data structures
122+
120123
### 1.2.0
121124
- add `Decode.flatMap`
122125

examples/Recursive.res

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
type rec t = {value: int, next: option<t>}
2+
3+
module Decode = {
4+
open Json.Decode
5+
6+
let rec list = () => object(field => {
7+
value: field.required(. "value", int),
8+
next: field.optional(. "next", indirect(list)),
9+
})
10+
}

src/Json_Decode.res

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,8 @@ let flatMap = (decodeA, f) => (. json) => {
242242
decodeB(. json)
243243
}
244244

245+
let indirect = f => (. json) => f()(. json)
246+
245247
let decode = (json, decode) =>
246248
try Ok(decode(. json)) catch {
247249
| DecodeError(msg) => Error(msg)

src/Json_Decode.resi

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,6 @@ let oneOf: array<t<'a>> => t<'a>
3737
let map: (t<'a>, (. 'a) => 'b) => t<'b>
3838
let flatMap: (t<'a>, (. 'a) => t<'b>) => t<'b>
3939

40+
let indirect: (() => t<'a>) => t<'a>
41+
4042
let decode: (Js.Json.t, t<'a>) => result<'a, string>

0 commit comments

Comments
 (0)