vault backup: 2023-11-13 13:50:53
This commit is contained in:
92
Algo/B1/Séminaire/Chapter 4 - A bit of imperative.md
Normal file
92
Algo/B1/Séminaire/Chapter 4 - A bit of imperative.md
Normal file
@ -0,0 +1,92 @@
|
||||
|
||||
<center><img src="https://gitea.louisgallet.fr/lgallet/epicours/raw/branch/main/Algo/S%C3%A9minaire/assets/unitaire-meme.png " width=auto height=400 /> </center>
|
||||
|
||||
|
||||
## 0.1. Print
|
||||
If we want to print something in CAML, we have to use this structure
|
||||
|
||||
```Ocaml
|
||||
# print_string "Hello World!";;
|
||||
Hello! - : unit=()
|
||||
|
||||
# print_int ;;
|
||||
-: int -> unit = <fun>
|
||||
|
||||
(*expression*)
|
||||
# print_[type] [things to print];;
|
||||
[things to print] -: unit=()
|
||||
```
|
||||
|
||||
**Difference between compiler and interpreter for print**
|
||||
```mermaid
|
||||
flowchart LR
|
||||
|
||||
A[CAML] -- compile --> B[ ] -- exec --> C[standard output] & D[standard error] ~~~ E(on your terminal)
|
||||
```
|
||||
```mermaid
|
||||
flowchart LR
|
||||
|
||||
A[CAML] -- interpreter --> B[standard error] & C[standard output] & D[CAML answer] ~~~ E(in the interpreter interface)
|
||||
```
|
||||
|
||||
**To print something and create a new line for the CAML evaluation**
|
||||
```Ocaml
|
||||
# print_endline "toto";;
|
||||
toto
|
||||
-: unit = ()
|
||||
```
|
||||
**To just print a newline**
|
||||
```Ocaml
|
||||
# print_newline();;
|
||||
-: unit = ()
|
||||
|
||||
(* example *)
|
||||
# print_newline(print_int 54);;
|
||||
54
|
||||
-: unit = ()
|
||||
```
|
||||
|
||||
## 0.2. Sequence of prints
|
||||
To print two things on the same line we have to use this structure
|
||||
```Ocaml
|
||||
# print_string "The answer is: "; print_int 42;;
|
||||
The answer is: 42 -: unit = ()
|
||||
|
||||
# 3*2*7; print_string "The answer is : ";;
|
||||
The answer is -: unit = ()
|
||||
Warning 10 [non-unit-statement]: this expression should have type unit.
|
||||
|
||||
# print_string "The answer is: "; 3*2*7;;
|
||||
The answer is: -:int = 42
|
||||
```
|
||||
|
||||
### 0.3. Print in a function
|
||||
```OCaml
|
||||
# let print_even n =
|
||||
if n mod 2 = 0 then
|
||||
print_int n;;
|
||||
(*Caml will automaticaly add the else with a empty value ()*)
|
||||
val print_even: int -> unit = <fun>
|
||||
|
||||
# print_even 4;;
|
||||
4 -: unit = ()
|
||||
|
||||
# print_even 7;;
|
||||
-: unit = ()
|
||||
|
||||
# let ret_even n =
|
||||
if n mod 2 = 0 then
|
||||
n;;
|
||||
Error: should have int type (*because of the hidden else*)
|
||||
|
||||
# let print_even n =
|
||||
if n mod 2 = 0 then
|
||||
begin
|
||||
print_int n ;
|
||||
print_newline()
|
||||
end;; (*begin and end used to execute more than 1 function into a if*)
|
||||
val print_even : int -> unit = <fun>
|
||||
|
||||
# print_even 4;;
|
||||
4
|
||||
-: unit = ()
|
Reference in New Issue
Block a user