我对以下功能有疑问我想做拉链功能;例如)zip [1; 2; 3; 4] [5; 6; 7; 8]然后结果= [1; 5; 2; 6; 3; 7; 4; 8]那就是我想要的,所以我发挥了作用。line#4 h2 :: t2使错误语法错误:预期模式我不知道是什么问题请帮我 !!!谢谢
let rec zip lst1 lst2 =
match lst1 lst2 with
| [] [] -> []
| h1::t1 h2::t2 -> h1 h2::zip t1 t2
|_ _ -> failwith "The lists seems to have different lengths";;
模式match
一次只能与one表达式匹配。如果要与two列表(即两个表达式)匹配,则需要将它们组合为一个表达式。惯用的方法是使用tuple,将它们配对,例如::
match lst1, lst2 with
| [], [] -> []
| h1::t1, h2::t2 -> (h1, h2)::(zip t1 t2)
| _ -> failwith "Cannot zip lists of different lengths"
将表达式放入元组的语法技术上为(e1, e2, ..., en)
;但是当它是明确的时当被其他优先使用的符号或关键字包围时,OCaml允许省略括号并仅使用逗号。