-2

我想做一个叫做 zip 的函数,所以:
zip [1;2;3;4] [5;6;7;8] 会产生: [1;5;2;6;3;7;4;8]

但我收到一个错误:line#4 h2::t2 make error syntax error : pattern expected

什么是正确的语法?

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";;


4

1 回答 1

1

一个模式match一次只能匹配一个表达式。如果您想匹配两个列表,即两个表达式,您需要将它们组合成一个表达式。这样做的惯用方法是使用元组将它们配对,例如:

match lst1, lst2 with
| [], [] -> []
| h1::t1, h2::t2 -> (h1, h2)::(zip t1 t2)
| _ -> failwith "Cannot zip lists of different lengths"

从技术上讲,将表达式放入元组的语法是(e1, e2, ..., en); 但是当它是明确的时,例如当被其他优先的符号或关键字包围时,OCaml 允许省略括号而只使用逗号。

于 2020-03-24T03:06:57.207 回答