How to pattern match a function in OCaml

Viewed 37

I need a function that takes an argument and if it happens to be a function, it calls it, i.e. something like

let foo x y =
   match x with
   | Fun -> x y
   | _ -> y

but I wasn't able to find out how this could be done. What is the proper pattern-matching syntax here?

1 Answers

OCaml is a strongly typed language with parametric polymorphism, a value is either always a function or never. In particular, it is not possible to match on the type of a value. In some sense, types are metadata that describe your program, but they are not part of your program.

What you can do is define a new variant type, whose some constructor may contain some functions. For instance,

type ('a,'b) function_or_constant =
| Fun of ('a -> 'b)
| Const of 'b

let eval f x = match f with
| Fun f -> f x
| Const y -> y
Related