Created
January 31, 2024 04:30
-
-
Save dmmulroy/9ed66b10933285602bf3c5a041b51f86 to your computer and use it in GitHub Desktop.
melange-json-test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Color = struct | |
type t = Red | Green | Blue | |
let to_string = function Red -> "red" | Green -> "green" | Blue -> "blue" | |
let of_json json = | |
Json.Decode.( | |
field "kind" string json |> function | |
| "red" -> Red | |
| "green" -> Green | |
| "blue" -> Blue | |
| _ -> failwith "Invalid color") | |
;; | |
let to_json = function | |
| Red -> Json.Encode.(object_ [ ("kind", string "red") ]) | |
| Green -> Json.Encode.(object_ [ ("kind", string "green") ]) | |
| Blue -> Json.Encode.(object_ [ ("kind", string "blue") ]) | |
;; | |
end | |
let main () = | |
let json = Json.Encode.(object_ [ ("kind", string "red") ]) in | |
let color = Color.of_json json in | |
Js.log (Color.to_string color) | |
;; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Generated by Melange | |
import * as Json__Json_decode from "melange-json/Json_decode.mjs"; | |
import * as Json__Json_encode from "melange-json/Json_encode.mjs"; | |
import * as Stdlib from "melange/stdlib.mjs"; | |
function to_string(param) { | |
switch (param) { | |
case /* Red */ 0: | |
return "red"; | |
case /* Green */ 1: | |
return "green"; | |
case /* Blue */ 2: | |
return "blue"; | |
} | |
} | |
function of_json(json) { | |
var param = Json__Json_decode.field("kind", Json__Json_decode.string, json); | |
switch (param) { | |
case "blue": | |
return /* Blue */ 2; | |
case "green": | |
return /* Green */ 1; | |
case "red": | |
return /* Red */ 0; | |
default: | |
return Stdlib.failwith("Invalid color"); | |
} | |
} | |
function to_json(param) { | |
switch (param) { | |
case /* Red */ 0: | |
return Json__Json_encode.object_({ | |
hd: ["kind", "red"], | |
tl: /* [] */ 0, | |
}); | |
case /* Green */ 1: | |
return Json__Json_encode.object_({ | |
hd: ["kind", "green"], | |
tl: /* [] */ 0, | |
}); | |
case /* Blue */ 2: | |
return Json__Json_encode.object_({ | |
hd: ["kind", "blue"], | |
tl: /* [] */ 0, | |
}); | |
} | |
} | |
var Color = { | |
to_string: to_string, | |
of_json: of_json, | |
to_json: to_json, | |
}; | |
function main(param) { | |
var json = Json__Json_encode.object_({ | |
hd: ["kind", "red"], | |
tl: /* [] */ 0, | |
}); | |
var color = of_json(json); | |
console.log(to_string(color)); | |
} | |
export { Color, main }; | |
/* No side effect */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment