Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml: Using a comparison operator passed into a function

I'm an OCaml noob. I'm trying to figure out how to handle a comparison operator that's passed into a function.

My function just tries to pass in a comparison operator (=, <, >, etc.) and an int.

let myFunction comparison x = 
if (x (comparison) 10) then 
   10
else
   x;;

I was hoping that this code would evaluate to (if a "=" were passed in):

if (x = 10) then
   10
else
   x;;

However, this is not working. In particular, it thinks that x is a bool, as evidenced by this error message:

This expression has type 'a -> int -> bool
but an expression was expected of type int

How can I do what I'm trying to do?

On a side question, how could I have figured this out on my own so I don't have to rely on outside help from a forum? What good resources are available?

like image 857
Casey Patton Avatar asked Sep 26 '11 02:09

Casey Patton


1 Answers

Comparison operators like < and = are secretly two-parameter (binary) functions. To pass them as a parameter, you use the (<) notation. To use that parameter inside your function, you just treat it as function name:

let myFunction comp x = 
  if comp x 10 then 
     10
  else
     x;;

printf "%d" (myFunction (<) 5);; (* prints 10 *)
like image 127
phooji Avatar answered Sep 18 '22 14:09

phooji