我有此数据类型
datatype json =
Num of real
| String of string
| False
| True
| Null
| Array of json list
| Object of (string * json) list
和此代码
fun mymatch (jobj,str) =
case jobj of
Array [] => NONE
| Array(Object oh::[]) => mymatch (Object oh, str)
| Array (Object oh::ot) =>
if isSome (assoc(str, oh)) then assoc(str, oh) else mymatch (Array ot, str)
| Object xs => assoc (str, xs)
| _ => NONE
具有此帮助功能
fun assoc (k, ls) =
case ls of
[] => NONE
| (a,b)::[] => if k = a then SOME b else NONE
| (a,b)::xs => if k = a then SOME b else assoc (k,xs)
应该采取这样的方式
mymatch (Array [Object [("n", Num (4.0)),("b", True)],Object [("last", Num (4.0)),("foo", True)]],"foo")
并在string
“ foo”上返回一个匹配项,在Object
中搜索每个Array
。如您在代码中看到的,我实际上只处理json
中符合比赛条件的两件事,即Array
包含Objects
,然后发送Object
进行检查。这段代码有效,但是肯定来自野蛮编程学院,即感觉就像是一团糟。为什么?由于mymatch
中的情况,我需要通过Array
向下递归
... | Array (Object oh::ot) => if isSome (assoc(str, oh)) then assoc(str, oh) else mymatch (Array ot, str) ...
直到现在,我只在检查车的列表上处理递归,然后在cdr上递归。同样,此代码有效,但是我可以感觉到我缺少了一些东西。我需要检查
Object
的头部Array
,如果匹配则终止。否则,请继续递归-全部在option
返回范围内。有没有更优雅的方法?
我有此数据类型,数据类型json =实数|字串|错误|是的空| json列表数组| (字符串* json)列表的对象,此代码很有趣...
编写用于匹配数组“内部”的函数: