gpt4 book ai didi

function - 为什么不能像 OCaml 中的常规函数​​一样传递数据构造函数?

转载 作者:行者123 更新时间:2023-12-03 23:33:19 24 4
gpt4 key购买 nike

例如,考虑以下代码:

type foo = Foo of int

let apply z f = f z

(* This is not allowed *)
let create_foo = Foo

(* This is allowed *)
let create_foo i = Foo i

(* This is not allowed *)
apply 1 Foo

(* This is allowed *)
apply 1 create_foo
数据构造函数是必须完全应用的特殊功能吗?
当用作函数时, Foocreate_foo他们所做的事情是相同的。禁止使用 Foo 的原因是什么?作为可以传递和部分应用的常规函数​​?
Haskell 似乎允许这种行为。

最佳答案

来自马口,Xavier Leroy,在 this mailing list message from 2001 :

The old Caml V3.1 implementation treated constructors as functions like SML.In Caml Light, I chose to drop this equivalence for several reasons:

  • Simplicity of the compiler. Internally, constructors are notfunctions, and a special case is needed to transform Succ into(fun x -> Succ x) when needed. This isn't hard, but remember thatCaml Light was really a minimal, stripped-down version of Caml.

  • Constructors in Caml Light and OCaml really have an arity, e.g.C of int * int is really a constructor with two integer arguments,not a constructor taking one argument that is a pair. Hence, therewould be two ways to map the constructor C to a function:fun (x,y) -> C(x,y)orfun x y -> C(x,y)The former is more natural if you come from an SML background(where constructors have 0 or 1 argument), but the latter fits betterthe Caml Light / OCaml execution model, which favors curriedfunctions. By not treating constructors like functions, we avoidhaving to choose...

  • Code clarity. While using a constructor as a function is sometimesconvenient, I would argue it is often hard to read. Writing"fun x -> Succ x" is more verbose, but easier to read, I think.

关于function - 为什么不能像 OCaml 中的常规函数​​一样传递数据构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66833935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com