If I have this SML datatype
datatype json =
Num of real
| String of string
| False
| True
| Null
| Array of json list
| Object of (string * json) list
Let's say I have this Array
with only one Object
which makes it a json
list
Array[Object[("a", Num (1.0)),("b", True)]]
how can I cons a new Object
onto this existing Array
? I've tried a simple ::
to no avail
Object[("a", Num (1.0)),("b", True)]::Array[Object[("a", Num (2.0)),("b", True)]]
which gives an error. Do I have to build my own cons for this? It seems the SML list is 'a list
which should allow json list
and work with ::
Yes, this is a homework assignment from a past semester of Programming Languages at the U. of Washington that I'm doing on my own. This is the assignment.
My basic problem is I don't know how to add to an Array
with recursion calls. If I need to generate an Array
containing Objects
and add a new Object
to that starting Array
with each recursion call, how would that be done? I've seen examples of Succ
or Cons
, e.g., a successor constructor, but those just create a recursive, nested object such as
val four = Succ (Succ (Succ (Succ Zero)))
...but this isn't helpful...
Array [...]
is no a json list
, it's a json
, and ::
can't cons two json
s into a list.
You need to cons onto the list "inside" the Array
:
Array (Object [("a", Num 1.0)] :: ([Object [("a", Num 2.0)]]))
You probably want to add a "cons for JSON" function; something like
fun json_cons o (Array os) = Array (o :: os)
| json_cons _ _ = ... handle structural error ...
You can also invent your own binary infix operator, but that's probably a bit on the advanced side for this assignment.