« Return to Thread: A simple question about a function

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

by OLBA :: Rate this Message:

Reply to Author | View in Thread

Zitat von Msam85 <carloselcheca@...>:

>
> 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);;


================================================
oliver@siouxsie2:~$ ocaml
        Objective Caml version 3.09.2

# let op = function
  p->fst p (snd p);;
  val op : ('a -> 'b) * 'a -> 'b = <fun>
# op (fst, (2,3));;
- : int = 2
#  op (snd, (2,3));;
- : int = 3
# fst (2,3);;
- : int = 2
# snd (2,3);;
- : int = 3
# op (sin, 2.89);;
- : float = 0.248946786673152565
# let l = [(sin, 2.0); (sin, 3.0); (cos, 2.0) ];;
val l : ((float -> float) * float) list =
  [(<fun>, 2.); (<fun>, 3.); (<fun>, 2.)]
# List.map op l;;
- : float list =
[0.909297426825681709; 0.141120008059867214; -0.416146836547142407]
#
================================================




>
> 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>

Maybe it would make sense that you explain what you want to do,
so we can better find, what you did wrong.
Did you wrote this function and don't know how it works,
or is this an example you got from somewhere else and you want to
know what it does?


>
> Can somebody tell me how this function works and what does it do ?

It takes a pair as argument, and applies the first
member of the argument to the second member of the argument.

See the examples above.

Ciao,
   Oliver


 « Return to Thread: A simple question about a function