簡體   English   中英

OCaml:為什么`let f: int -> int list -> int list = (::);;` 會失敗?

[英]OCaml: Why does `let f : int -> int list -> int list = (::);;` fail?

我認為 OCaml 會閱讀

let f : int -> int list -> int list = (::);;

作為部分應用的實例,並將 function 存儲為f 但是,編譯器抱怨 function 應用於太少的 arguments。 任何對此的見解將不勝感激,謝謝。

OCaml 中的值::是構造函數,而不是一般的 function。 因此,它需要遵循 arguments(在括號中)。 您可以在(::)形式中使用它,但它必須后跟兩個括號中的值:

# ( :: ) (3, []);;
- : int list = [3]

其他構造函數也是如此,例如Some

# let f : 'a -> 'a option = Some
Error: The constructor Some expects 1 argument(s),
       but is applied here to 0 argument(s)

您當然可以像這樣定義您的 function:

let f : int -> int list -> int list = fun a b -> (::) (a, b)

或這個:

let f : int -> int list -> int list = fun a b -> a :: b

甚至像這樣:

let f : int -> int list -> int list = List.cons

(其他語言,特別是 Haskell,將構造函數視為函數。因此您可以使用部分應用的構造函數等。在我看來,這在美學上更優越,即看起來更優雅。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM