views:

62

answers:

2

Is it possible to use pattern matching over specified functions directly or with some exploits that don't involve specifying a type for every function I need?

Just to explain things better suppose I have a type like

type BBoolOp = (bool->bool->bool)*term*term

and suppose that the bool->bool->bool functions are some quite simple like just (&&) (||)..

is it possible to do different things depending on the function that is specified like:

match bop with
  (||) -> do something
  | (&&) -> do something else

This shouldn't be possible because functions can't be compared but maybe an exploit exists to do what I'm trying to do :)

Thanks in advance

+2  A: 

Functions can be tested for equality. Just be sure to compare functions and not temporary closures (and not with pattern-matching). And it will make code hard to read and fragile.

# (+) == (+);;
- : bool = false
# let f = (+);;
val f : int -> int -> int = <fun>
# f == f;;
- : bool = true
ygrek
I wouldn't do this. The language definition could change at any moment, and I wouldn't rely on being table to test functions in future versions.
Norman Ramsey
+5  A: 

Comparing functions is, as you mention, unsupported. In some cases it may work, but depending on that is not good IMO.

So I would just use an algebraic data type to solve this problem. You might be able to regain some of the flexibility of the pattern-matching-over-functions concept (not needing the pattern matching code to know of all possible operators) by using polymorphic variants. So either

type BBoolOper = And | Or
type BBoolOp = BBoolOper * term * term

or

type BBoolOp = [<`And | `Or] * term * term (* make opened/closed as needed *)
Michael E