Functional programming 我怎样才能使“有趣”[x]->;x`详尽无遗?

Functional programming 我怎样才能使“有趣”[x]->;x`详尽无遗?,functional-programming,pattern-matching,ocaml,Functional Programming,Pattern Matching,Ocaml,假设在Ocaml中,我具有以下功能: let f = fun [x] -> x 因此,我收到以下警告: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: [] 我的目标是从'a list->'a创建一个函数。我如何解释将[]传递给该函数的原因?您必须涵盖所有可能的情况。除了[x],您还可以有一个空列表和一个包含多个元素的列表: let f = funct

假设在Ocaml中,我具有以下功能:

let f = fun [x] -> x
因此,我收到以下警告:

this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
[]

我的目标是从
'a list->'a
创建一个函数。我如何解释将
[]
传递给该函数的原因?

您必须涵盖所有可能的情况。除了
[x]
,您还可以有一个空列表和一个包含多个元素的列表:

let f = function 
    |[x] -> x
    | _ -> failwith "bad entry";;

如果
[x]
不匹配,则通配符模式将匹配所有可能的值。

您只需决定当列表中有1个元素以外的元素时,函数应该做什么。jambono演示了如何在所有此类情况下使函数失败。另一个相当合理的函数总是返回列表的第一个元素,只有当列表为空时才会失败。此函数称为
List.hd

let f = List.hd
或者您也可以自己实施:

let f = function
| [] -> failwith "empty list"
| x :: _ -> x

在文档中,他们说,这个函数与包含1个以上变量的函数的乐趣是一样的(没有任何注释可以解释。你可以单独提问:-)
function…
fun whatever->match whatever与…