Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List 在Ocaml中迭代新类型_List_Recursion_Ocaml - Fatal编程技术网

List 在Ocaml中迭代新类型

List 在Ocaml中迭代新类型,list,recursion,ocaml,List,Recursion,Ocaml,因此,我将自己的类型定义为: type test = Empty | Int of int | Str of string | List of test list;; 我试图反复浏览列表并评估每个头部,但我似乎无法使其工作 type evalRes = Next /* | other matches just ignore this. It's needed for something else */;; let rec eval (test:test) : (evalRes) = match

因此,我将自己的类型定义为:

type test = Empty
| Int of int
| Str of string
| List of test list;;
我试图反复浏览列表并评估每个头部,但我似乎无法使其工作

type evalRes = Next /* | other matches just ignore this. It's needed for something else */;;
let rec eval (test:test) : (evalRes) = match test with
| Int i -> /* do int stuff */; Next
| Str s ->  /* string stuff */; Next
| List(stmt1::tail) -> eval stmt1;;

我知道这只会评估第一个。我如何让它评估列表的其余部分?而我的类型测试将有更多的案例需要匹配,这只是一个基本测试。

尾部有类型测试列表,这意味着您需要一些可以接受测试列表的函数。一个好的开始是查看List.map和List.fold。当然,在这种情况下,你们甚至不需要解构列表。困难的部分是决定如何合并每条语句的结果。

如果您真的想在尾部递归地应用eval,您需要将其转换回测试。这可以通过以下方式实现:

let rec eval (test:test) : evalRes = match test with
| Int i -> /* do int stuff */; Next
| Str s ->  /* string stuff */; Next
| List(stmt1::tail) -> (eval stmt1) ++ (eval (List tail))
显然,正如ivg所建议的,在这种情况下使用List.fold似乎更合适:

let rec eval (test:test) : evalRes = match test with
| Int i  -> /* do int stuff */; Next
| Str s  -> /* string stuff */; Next
| List l -> List.fold_left (fun res test -> res ++ (eval test)) Next l
其中,++是处理求值序列的方法

可能还有比这更有趣的事

let (++) a b = b