97 lines
2.0 KiB
Markdown
97 lines
2.0 KiB
Markdown
|
|
<center><img src="https://gitea.louisgallet.fr/lgallet/epicours/raw/branch/main/Algo/S%C3%A9minaire/assets/functions-meme.jpg " width=auto height=400 /> </center>
|
|
|
|
|
|
## 2.1. One parameter function
|
|
```Ocaml
|
|
# 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)
|
|
|
|
```Ocaml
|
|
# 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
|
|
```
|
|
|
|
```Ocaml
|
|
# let successor_of_double x=f(gx);;
|
|
val successor_of_double: int -> int = <fun>
|
|
|
|
# successor_of_double (-12);;
|
|
_: int = -23
|
|
```
|
|
|
|
#### Existing functions
|
|
```Ocaml
|
|
# 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
|
|
```Ocaml
|
|
# 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)
|
|
|
|
```Ocaml
|
|
(*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
|
|
```
|
|
|