admin管理员组文章数量:1123509
In below snippet, the recursive function lookup
has only one parameter.
How could it later be applied with two parameters k
and t
?
let rec lookup k = function (* only 1 parameter k *)
| [] -> None
| (k', v) :: t ->
if k = k' then Some v
else lookup k t (* applied with 2 parameters k and t *)
In below snippet, the recursive function lookup
has only one parameter.
How could it later be applied with two parameters k
and t
?
let rec lookup k = function (* only 1 parameter k *)
| [] -> None
| (k', v) :: t ->
if k = k' then Some v
else lookup k t (* applied with 2 parameters k and t *)
Share
Improve this question
edited 14 hours ago
Chris
36.3k5 gold badges31 silver badges54 bronze badges
asked 20 hours ago
smwikipediasmwikipedia
64k96 gold badges326 silver badges504 bronze badges
3
- Hint: Where do you think the list you match on comes from? – glennsl Commented 20 hours ago
- I can apply lookup with an additional list argument. But that doesn’t comply with the let definition. But it can work. Strange. – smwikipedia Commented 19 hours ago
- I know about the partial application. But this seems like some over application… – smwikipedia Commented 19 hours ago
3 Answers
Reset to default 3All functions take one parameter, and lookup k t
is equivalent to (lookup k) t
.
lookup k
is also a function that takes one parameter - that's what let rec lookup k = function ...
means.
However, that parameter is not named, but used only in the pattern-matching clause.
Your definition is (at least more or less) equivalent to
let rec lookup k = fun table -> match table with
| [] -> None
| (k', v) :: t -> if k = k' then Some v else lookup k t
which is the same as
let rec lookup k table = match table with
| [] -> None
| (k', v) :: t -> if k = k' then Some v else lookup k t
but avoids the match
and the naming of the parameter whose name is only used for the matching.
You defined lookup k
as a function
, so lookup k
can be applied to t
. See https://ocaml.org/manual/5.3/expr.html#sss:expr-function-definition
Another way of looking at your function in terms of OCaml functions only taking one parameter is that lookup
generates a closure: a function that iterates recursively over a list knowing which value to look for.
let lookup k =
let rec aux t =
match t with
| [] -> None
| (k', v)::_ when k = k' -> Some v
| _::tl -> aux tl
in
aux
Also note that you've just implemented List.assoc_opt
from the standard library.
本文标签: ocamlWhy the number of function parameters doesn39t match the function definitionStack Overflow
版权声明:本文标题:ocaml - Why the number of function parameters doesn't match the function definition? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736577680a1944893.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论