ocaml

Why the number of function parameters doesn't match the function definition?


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 *)

ADD 1 - 2:44 PM 1/24/2025

OCaml function only takes one parameter.

There are 2 syntactic forms of function definition (ref).

Form 1:

enter image description here|200

In form 1, the parameter is only used for pattern matching. The function body expression doesn't directly use the parameter so the parameter doesn't need to be explicitly listed/named.

Form 2:

enter image description here

In form 2, the function body expression does directly use the parameter so the parameter must be explicitly listed/named.

My lookup is defined as a functional value that maps a value of type 'a to a functional value of type ('a * 'b) list -> 'b option.

My lookup k is a functional value that maps a value of type ('a * 'b) list to a value of 'b option.

So in practice, the application of lookup 1 evaluates to a functional value that takes a (int * 'b) list and returns a value of 'b type.

This functional value can be further applied to a value of the type (int * 'b) list.


Solution

  • 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