在OCaml中混合模式匹配和currying

Jam*_*pel 9 ocaml

在SML中,使用currying和pattern匹配来定义函数是很常见的.这是一个简单的例子:

fun zip [] _ = []
  | zip _ [] = []
  | zip (x::xs) (y::ys) = (x,y)::(zip xs ys)
Run Code Online (Sandbox Code Playgroud)

忽略库函数,将此端口移植到OCaml的最佳方法是什么?据我所知,没有简单的方法来使用currying和pattern匹配声明一个函数.

小智 11

我会说最好只使用匹配表达式.

let rec zip xs ys = 
    match xs, ys with
    | [], _
    | _, [] -> []
    | x :: xs, y :: ys -> (x, y) :: zip xs ys
Run Code Online (Sandbox Code Playgroud)

如果你没有使用匹配,那就有点复杂,但是你可以做到这一点.

let rec zip = function
    | [] -> (fun _ -> [])
    | x :: xs ->
        function 
        | [] -> []
        | y :: ys -> (x, y) :: zip xs ys
Run Code Online (Sandbox Code Playgroud)