2

在 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. 我如何解释[]被传递给该函数?

4

2 回答 2

5

您只需要决定当列表包含 1 个以外的元素时您的函数应该做什么。jambono 展示了如何在所有此类情况下使功能失败。另一个相当合理的函数将始终返回列表的第一个元素,并且只有在列表为空时才会失败。这个函数被称为List.hd

let f = List.hd

或者您可以自己实现它:

let f = function
| [] -> failwith "empty list"
| x :: _ -> x
于 2013-08-31T17:36:35.740 回答
1

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

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

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

于 2013-08-31T17:12:54.637 回答