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
OCaml:List.iter从匹配后的下一个元素开始_List_Functional Programming_Ocaml - Fatal编程技术网

OCaml:List.iter从匹配后的下一个元素开始

OCaml:List.iter从匹配后的下一个元素开始,list,functional-programming,ocaml,List,Functional Programming,Ocaml,我发现了一件奇怪的事: 在我的代码中,我想输出包含特殊类型元素的列表的数据,该元素由另一种类型和name组成 我以前从来都不需要这样的代码,所以我不知道为什么它不起作用或者被禁止或者类似的东西 List.iter( fun x -> ( fprintf oc "("; fprintf oc "asdf"; match x.kind with |Id -> fprintf oc "Id" |Op -

我发现了一件奇怪的事:

在我的代码中,我想输出包含特殊类型元素的列表的数据,该元素由另一种类型和
name
组成

我以前从来都不需要这样的代码,所以我不知道为什么它不起作用或者被禁止或者类似的东西

List.iter(
    fun x -> (
        fprintf oc "(";
        fprintf oc "asdf";
        match x.kind with
        |Id -> fprintf oc "Id"
        |Op -> fprintf oc "Op"
        |Test -> fprintf oc "Test"
        ;  
        fprintf oc "fdsa";
        fprintf oc "%s" x.name;
        fprintf oc "),";
    )   
)list;
asdf和fdsa是测试输出,用于查看问题所在。 oc是我写入文件的输出通道,其余的应该是安静的自我解释,对于像您这样的Ocaml专业人士:)

不幸的是,我只能得到这样的结果:
(asdfId)(asdfOp)(asdfId
),因此,似乎在匹配后停止执行,他继续执行列表中的下一个元素

预期输出将是
(asdfdfdsatest1)、(asdfOpfdsatest2)

我不能把x.name移到顶部,因为我需要右括号


我做错了什么,我遗漏了一个错误吗?有人知道如何输出我的数据吗?

在OCaml中,match的优先级高于
。因此,您需要将
match
放在一对括号中

让我们在toplevel中尝试以下操作:

> match 0 with
   | 0 -> print_string "zero "
   | _ -> print_string "non-zero";
  print_endline "42";;

Output: zero 
现在,让我们在
match
表达式周围添加括号:

> (match 0 with
   | 0 -> print_string "zero "
   | _ -> print_string "non-zero");
  print_endline "42";;

Output: zero 42

旁注:在现实生活中,最好使用
if
表达式对整数进行那种“模式匹配”。

缩进代码的标准方法是:

List.iter (fun x ->
    fprintf oc "(";
    fprintf oc "asdf";
    match x.kind with
    |Id -> fprintf oc "Id"
    |Op -> fprintf oc "Op"
    |Test -> fprintf oc "Test"
        ;
        fprintf oc "fdsa";
        fprintf oc "%s" x.name;
        fprintf oc "),";
  ) list;
在这里,您可以看到最后3条语句仅在第3个分支中执行

为了解决这个问题,您可以用这种方式重写代码(第一种方式是通常的方式,从我所看到的:

List.iter (fun x ->
    fprintf oc "(";
    fprintf oc "asdf";
    begin match x.kind with
    |Id -> fprintf oc "Id"
    |Op -> fprintf oc "Op"
    |Test -> fprintf oc "Test"
    end;
    fprintf oc "fdsa";
    fprintf oc "%s" x.name;
    fprintf oc "),";
  ) list;


使用适当的OCaml代码缩进工具来避免此类错误,例如OCaml模式、tuareg模式或ocp缩进。它们缩进的行与您的意图不同。
List.iter (fun x ->
    fprintf oc "(";
    fprintf oc "asdf";
    (match x.kind with
     |Id -> fprintf oc "Id"
     |Op -> fprintf oc "Op"
     |Test -> fprintf oc "Test");
    fprintf oc "fdsa";
    fprintf oc "%s" x.name;
    fprintf oc "),";
  ) list;