1.4 KiB
1.4 KiB
2.1. One parameter function
# let successor x=x+1;;
val successor: int -> int =<fun>
# successor;;
_ : int -> int =<fun>
# successor 3;;
_: int = 4
# successor (-1)::
_: int = 0
x
is call a formal parameter andx+1
is call the body of the function.3
is an effective parameter (= argument). For the last line, the paratheses are needed, without it, CAML will return an error
⚠️ f x = f(x)
and ``fx+gy = (fx)+(gy)
# let f x = x+1 and g x = x*2
val f: int -> int = <fun>
val g: int -> int = <fun>
# fg 3;;
Error: was expecting an integer and get a function
# f(g 3);; *This way there is no error*
_: int = 7
# let successor_of_double x=f(gx);;
val successor_of_double: int -> int = <fun>
# successor_of_double (-12);;
_: int = -23
Existing functions
# sqrt;;
_: float -> float =<fun>
# int_of_float;;
_: float -> int =<fun>
# length "toto" ;;
Error : Unboud
# String.lenght "toto";; *String is a library*
_: int = 4
2.2. Functions and local definitions
# let pred x = x - 1 in pred 3 + pred 4;;
_: int = 6
# pred;;
Error
# let square_of_pred x = let pred_x = x - 1 in pred_x * pred_x;;
val square_of_pred: int -> int = <fun>
# square_of_pred 3;;
_: int = 4
# let square_of_pred x = let pred x = x - 1 in pred x * pred x
val square_of_pred: int -> int = <fun>
val pred: int -> int = <fun>
# square_of_pred 3;;
_: int = 4 *same things but with another method*