StormPooper
StormPooper

Reputation: 513

ocaml - best way to declare a function?

I'm new to ocaml, and I'm confused on a thing: when I declare a function, is there any difference between these way?

1)

let f e l = 
match l with
| []->[]
| h :: t -> if h=e then t else h :: f e t;;

2)

let e = function
h :: t -> if h=e then t else h :: f e t
| []->[];;

Upvotes: 0

Views: 228

Answers (1)

Anton Trunov
Anton Trunov

Reputation: 15404

No, not really in this case (when pattern-matching on the last argument to a "multi-argument" function). The function keyword allows you to make a functional value with one argument, and when the function is applied to a value, the value is pattern-matched against the patterns.

But if I tried to pattern-match on a non-last argument, I'd use the first variant. Here is a couple examples derived from the code in the question (I swapped e and l in the function's signature):

1) It's easy, we just copy the function's body and swap the arguments at all function application places:

let rec f l e = match l with
  | [] -> []
  | h :: t -> if h=e then t else h :: f t e

2) With function it's a bit cumbersome:

let rec f = function 
  | [] -> fun e -> []
  | h :: t -> fun e -> if h=e then t else h :: f e t

To understand why the second variant works, remember that multi-argument functions in OCaml are sequences of single-argument functions wrapped inside each other (it's called currying):

fun p_1 p_2 ... p_n -> body

is the same as

fun p_1 -> fun p_2 -> ... fun p_n -> body

Note: of course, if the function's body doesn't consist solely of the match construction, you can't use function.

Upvotes: 1

Related Questions