ocaml: phase 5.1 json_pretty.ml baseline (recursive ADT to string, len = 24)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Defines a JSON-like algebraic data type:
type json =
| JNull
| JBool of bool
| JInt of int
| JStr of string
| JList of json list
Recursively serialises to a string via match-on-constructor, then
measures the length:
JList [JInt 1; JBool true; JNull; JStr 'hi'; JList [JInt 2; JInt 3]]
-> '[1,true,null,"hi",[2,3]]' length 24
Exercises:
- five-constructor ADT (one nullary, three single-arg, one list-arg)
- recursive match
- String.concat ',' (List.map to_string xs)
- string-cat with embedded escaped quotes
34 baseline programs total.
This commit is contained in:
@@ -16,6 +16,7 @@
|
||||
"frequency.ml": 5,
|
||||
"fizzbuzz.ml": 57,
|
||||
"list_ops.ml": 30,
|
||||
"json_pretty.ml": 24,
|
||||
"lambda_calc.ml": 7,
|
||||
"levenshtein.ml": 11,
|
||||
"memo_fib.ml": 75025,
|
||||
|
||||
20
lib/ocaml/baseline/json_pretty.ml
Normal file
20
lib/ocaml/baseline/json_pretty.ml
Normal file
@@ -0,0 +1,20 @@
|
||||
type json =
|
||||
| JNull
|
||||
| JBool of bool
|
||||
| JInt of int
|
||||
| JStr of string
|
||||
| JList of json list
|
||||
|
||||
let rec to_string j =
|
||||
match j with
|
||||
| JNull -> "null"
|
||||
| JBool b -> if b then "true" else "false"
|
||||
| JInt n -> string_of_int n
|
||||
| JStr s -> "\"" ^ s ^ "\""
|
||||
| JList xs ->
|
||||
"[" ^ String.concat "," (List.map to_string xs) ^ "]"
|
||||
|
||||
;;
|
||||
|
||||
let j = JList [JInt 1; JBool true; JNull; JStr "hi"; JList [JInt 2; JInt 3]] in
|
||||
String.length (to_string j)
|
||||
Reference in New Issue
Block a user