在 OCaml 中混合模式匹配和柯里化

发布于 2024-12-04 08:39:44 字数 223 浏览 0 评论 0原文

在 SML 中,使用柯里化和模式匹配来定义函数是常见且容易的。这是一个简单的例子:

fun zip [] _ = []
  | zip _ [] = []
  | zip (x::xs) (y::ys) = (x,y)::(zip xs ys)

忽略库函数,将其移植到 OCaml 的最佳方法是什么?据我所知,没有简单的方法可以同时使用柯里化和模式匹配来声明函数。

In SML, it's common and easy to define a function using both currying and pattern matching. Here's a simple example:

fun zip [] _ = []
  | zip _ [] = []
  | zip (x::xs) (y::ys) = (x,y)::(zip xs ys)

Ignoring library functions, what's the best way to port this to OCaml? As far as I can tell, there is no easy way to declare a function using both currying and pattern matching.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲鸠 2024-12-11 08:39:44

我想说最好只使用匹配表达式。

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

如果您决定不使用匹配,这有点复杂,但您可以这样做。

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

I would say it's best to just use a match expression.

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

If you're set on not using match, it's a bit convoluted, but you can do this.

let rec zip = function
    | [] -> (fun _ -> [])
    | x :: xs ->
        function 
        | [] -> []
        | y :: ys -> (x, y) :: zip xs ys
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文