0
votes

I am new to Ocaml and I have a question about pattern matching in Ocaml. If I have the following type definition:

type t = False | True | Function (t -> t)

How can I match a term that is Function (t -> t)? So far the only thing I can do is match Function f. But is there any way to match the argument to the function? Ideally it'd be nice to have something like

match t with
| Function (t1 -> t2) -> ...
| ...

But apparently it is not the correct syntax. Is it even possible?

2

2 Answers

1
votes

It sounds like you're trying to extract something of type t from a function value of type t -> t, but I don't think this makes sense. If something is of type t -> t, then it's a function that accepts a value of type t and returns a value of the same type. However if you have a value of this (function) type, you don't have something with two parts, each of which is of type t. Even if you think abstractly, a function is a set of pairs of values, not a single pair of values.

It may be that what you want to do is to represent pairs of values each of which is of type t. That would look something like this:

type t = False | True | Pair of t * t

Now you can extract the components of a Pair with a pattern match. But a pair of values is not a function (unless you restrict your idea of functions to very trivial ones with a singleton domain and range I guess).

0
votes

Pattern matching matches the structure of the value. What you are trying to do is match the type which you can't.

It also makes no sense. In

type t = False | True | Function (t -> t)

the Function always has type t -> t. If you already matched that it is a Function then you already know it is t -> t. There is no further choice that you could match against.

You also can't do

match t with Function my_function -> ...

but you can do

match t with Function f when f == my_function -> ...

I think.