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
Add a comment  | 

3 Answers 3

Reset to default 3

All 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