« Return to Thread: A simple question about a function

Re: "ocaml_beginners"::[] A simple question about a function

by Jon Harrop :: Rate this Message:

Reply to Author | View in Thread

On Friday 03 August 2007 00:17:50 Msam85 wrote:
> HI everyone.
>
> I'm new in Ocaml language, and I had tried to understand the following
> function, but Im not able.
>
> let op = function
>   p->fst p (snd p);;

This is equivalent to:

  let op p = fst p (snd p)

Pattern matching makes deconstruction faster and more readable, so it is even
easier to write:

  let op (f, x) = f x

So the "op" function accepts a pair and applies the second element of the pair
to the first element of the pair.

> If I put it at the top level it shows me :
> val op :     ('a->'b)*'a ->'b = <fun>
>
> I think that p must be like ( , )  but if i trie to write op((+),3);;
> It shows me   -: int -> int = <fun>

Yes. That takes the curried "add" function and partially applies "3" to give a
function that adds three:

# let op (f, x) = f x;;
val op : ('a -> 'b) * 'a -> 'b = <fun>
# let add_three = op((+), 3);;
val add_three : int -> int = <fun>
# add_three 5;;
- : int = 8

--
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
OCaml for Scientists
http://www.ffconsultancy.com/products/ocaml_for_scientists/?e

 « Return to Thread: A simple question about a function