Skip to content

Commit

Permalink
refactor Decode
Browse files Browse the repository at this point in the history
  • Loading branch information
liyishuai committed Sep 20, 2024
1 parent 8ae6b72 commit d63ba70
Showing 1 changed file with 18 additions and 19 deletions.
37 changes: 18 additions & 19 deletions Decode.v
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,21 @@ Open Scope json_scope.

Class JDecode T := decode : json -> string + T.

#[global]
Instance Monad__JDecode: Monad JDecode :=
{ ret _ := const ∘ inr;
bind _ _ f k j := f j >>= flip k j
}.

#[global]
Instance MonadExc__JDecode: MonadExc string JDecode :=
{ raise _ := const ∘ inl;
catch _ m f j := match m j with
| inl e => f e j
| inr _ as mj => mj
end
}.

#[global]
Instance JDecode__json : JDecode json := inr.

Expand All @@ -35,11 +50,11 @@ Instance JDecode__Z : JDecode Z :=

#[global]
Instance JDecode__N : JDecode N :=
fmap Z.to_N decode.
Z.to_N <$> decode.

#[global]
Instance JDecode__nat : JDecode nat :=
fmap Z.to_nat decode.
Z.to_nat <$> decode.

#[global]
Instance JDecode__bool : JDecode bool :=
Expand All @@ -56,8 +71,7 @@ Definition decode__list {T} `{JDecode T} : JDecode (list T) :=
else inl $ "Not an Array: " ++ to_string j.

Definition decode__option {T} `{JDecode T} : JDecode (option T) :=
fun j : json =>
catch (Some <$> decode j) (const $ inr None).
catch (Some <$> decode) (const $ pure None).

#[global]
Instance JDecode__unit : JDecode unit :=
Expand All @@ -80,18 +94,3 @@ Definition dpath' {T} (d : JDecode T) (s : string) (j : json) : string + T :=
(decode__jpath (this@s) j <|> inr JSON__Null) >>= d.

Definition dpath {T} `{JDecode T} : string -> JDecode T := dpath' decode.

#[global]
Instance Monad__JDecode: Monad JDecode :=
{ ret _ := const ∘ inr;
bind _ _ f k j := f j >>= flip k j
}.

#[global]
Instance MonadExc__JDecode: MonadExc string JDecode :=
{ raise _ := const ∘ inl;
catch _ m f j := match m j with
| inl e => f e j
| inr _ as mj => mj
end
}.

0 comments on commit d63ba70

Please sign in to comment.