Zulip Chat Archive
Stream: new members
Topic: JSON as a string example in Functional Programming book
Lars Ericson (Aug 02 2023 at 19:07):
@David Thrane Christiansen , this example needs an import Lean.Data.Json
to run, not currently in the text:
import Lean.Data.Json -- required
inductive JSON where
| true : JSON
| false : JSON
| null : JSON
| string : String → JSON
| number : Float → JSON
| object : List (String × JSON) → JSON
| array : List JSON → JSON
deriving Repr
structure Serializer where
Contents : Type
serialize : Contents → JSON
def Str : Serializer :=
{ Contents := String,
serialize := JSON.string
}
instance : CoeFun Serializer (fun s => s.Contents → JSON) where
coe s := s.serialize
def buildResponse (title : String) (R : Serializer) (record : R.Contents) : JSON :=
JSON.object [
("title", JSON.string title),
("status", JSON.number 200),
("record", R record)
]
#eval buildResponse "Functional Programming in Lean" Str "Programming is fun!"
#eval (5 : Float).toString
def dropDecimals (numString : String) : String :=
if numString.contains '.' then
let noTrailingZeros := numString.dropRightWhile (· == '0')
noTrailingZeros.dropRightWhile (· == '.')
else numString
def String.separate (sep : String) (strings : List String) : String :=
match strings with
| [] => ""
| x :: xs => String.join (x :: xs.map (sep ++ ·))
partial def JSON.asString (val : JSON) : String :=
match val with
| true => "true"
| false => "false"
| null => "null"
| string s => "\"" ++ Lean.Json.escape s ++ "\""
| number n => dropDecimals n.toString
| object members =>
let memberToString mem :=
"\"" ++ Lean.Json.escape mem.fst ++ "\": " ++ asString mem.snd
"{" ++ ", ".separate (members.map memberToString) ++ "}"
| array elements =>
"[" ++ ", ".separate (elements.map asString) ++ "]"
#eval (buildResponse "Functional Programming in Lean" Str "Programming is fun!").asString
David Thrane Christiansen (Aug 06 2023 at 19:09):
Thanks for letting me know! The source code for that chapter's examples doesn't include this line, but it's loading something else that results in that library being available. I'm really busy right now, and I'll fix this when I can - in the meantime, it's tracked here: https://github.com/leanprover/fp-lean/issues/122
Thanks again!
David Thrane Christiansen (Oct 03 2023 at 07:41):
This is fixed - the improvement will be in the upcoming release. Thanks!
Last updated: Dec 20 2023 at 11:08 UTC