timbo
timbo

Reputation: 14314

OCaml match shorthand

When I first looked at the use of the function keyword in OCaml, I gained the impression that it was syntax sugar to eliminate the match x with line for a pattern match.

However, I see that there is a signature difference between the two as in the example below. In what circumstances would you wish to use the function example?

type e = Foo | Bar

let eval1 exp =
match exp with
| Foo -> "Foo"
| Bar -> "Bar"

let eval2 exp = function
| Foo -> "Foo"
| Bar -> "Bar"

The first function has a signature of val eval1 : e -> bytes = <fun>

The second function has a signature of val eval2 : 'a -> e -> bytes = <fun>

Upvotes: 1

Views: 458

Answers (1)

glennsl
glennsl

Reputation: 29106

In eval2, using function, the argument that is matched on is implicit. exp is unused here, and should give you a compiler warning (unless you've turned it off). If you remove the exp argument the signatures should be identical.

Or in other words, function ... is not syntax sugar for just match exp with ..., but for fun exp -> match exp with ...

Upvotes: 8

Related Questions