epicours/Algo/B1/Séminaire/Chapter 2 - Functions.md

2.0 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 and x+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*)

2.3. Function with several parameters (2 or more)

(*The logic way (for us)*)
# let average(a,b) = (a+b)/2 ;;
val average: int*int -> int = <fun>

(*This method is not for several parameter, is just a one parameter wich is a couple*) (*f(x,y) ≠ f x y*)

(*The OCaml way (the way that it work) *)
# let average a b = (a+b)/2;;
val average: int -> int -> int = <fun>
# average (-2) (2);;
-: int = 0