Tre*_*ing 2 ocaml functional-programming pattern-matching
在Ocaml中说我有以下功能:
let f = fun [x] -> x
Run Code Online (Sandbox Code Playgroud)
结果我得到以下警告:
this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
[]
Run Code Online (Sandbox Code Playgroud)
我的目标是从中创建一个函数'a list -> 'a.我如何考虑[]传递给该功能?
当列表不是1个元素时,你只需要决定你的函数应该做什么.jambono展示了如何在所有这些情况下使函数失败.另一个相当合理的函数将始终返回列表的第一个元素,并且只有在列表为空时才会失败.这个功能被称为List.hd.
let f = List.hd
Run Code Online (Sandbox Code Playgroud)
或者你可以自己实现它:
let f = function
| [] -> failwith "empty list"
| x :: _ -> x
Run Code Online (Sandbox Code Playgroud)