How to play with first class function in ocaml


#1

Hi,
Can any one tell me please tell me how to make simple application with this type of function,
I want to make this function let doub y x=x*y as first calss. i know the difinition but i cant understand how to implement it.

type test =
{
fonc: (int -> int) ;
(* An argument, which will be given to the function. )
arg: int ;
(
The expected result. *)
expect: int }


#2

The problem happens when you try to create a value of this record type:

# type test = { fonc : int -> int; arg : int; expect : int };;
type test = { fonc : int -> int; arg : int; expect : int; }
# let test1 = { fonc = fun x -> x; arg = 1; expect = 1 };;
Error: Unbound value arg

This happens because the semi-colon (;) is overloaded in OCaml, it means both ‘record member separator’ and ‘sequencing operator’. In this case OCaml is thinking you meant the latter while you really meant the former. To fix this, you’ll need to make OCaml understand that you meant the former, using parentheses:

# let test1 = { fonc = (fun x -> x); arg = 1; expect = 1 };;
val test1 : test = {fonc = <fun>; arg = 1; expect = 1}

#3

Ok. Thank you, I need to know how to call test in ocaml ???


#4

Given what @yawaramin wrote:

# test1.fonc test1.arg;;
- : int = 1
# test1.fonc test1.arg = test1.expect;;
- : bool = true