## 3.1. The alternative ### The if structure ```Ocaml if cond then expr1 else expr2 ``` > ⚠️ `expr1` and `expr2` have to be the same type. `cond` is a `bool` **For exemple** ```Ocaml # if 1<2 then "higher" else "lower" ;; -: string = "higher" ``` **Exercise : absolute program** ```Ocaml # let abs(x) = if x>0 then x else -x ;;; val abs : int -> int ``` ## 3.2. Exceptions ### Division by 0: ```Ocaml # 1/0 Exception : Division by zero ``` ### Failwith: Failwith is a function that take a string argument (the reason) and return the error. That way, we can raise an error into our code ```Ocaml # failwith;; -: string -> a = # failwith "oops";; Exception : Failwith "oops" ``` ### invalid_arg: Invalid_arg is a function that take a string argument (the reason) and return the error. That way, we can raison an error about an argument ```Ocaml # invalid_arg "oops"; Exception: Invalid_argument "oops" (*example*) # let div a b = if b = 0 then invalid_arg("div: b = 0") else a/b ;;; val div int -> int -> int = ``` ## 3.3. Filtering ### Explicit filtering > Explicit means that you matches the value **General syntax** ```Ocaml match expr with pattern1 -> result1 | pattern2 -> result2 | ... | patternn -> resultn ``` > All expressions and pattern must avec the same type **Example** ```Ocaml # let f x = match x with 0 -> 18 | 1 -> 24 | y -> y + y;; val f : int -> int = # f 1;; - : int = 24