2.5 KiB
2.5 KiB
3.1. The alternative
The if structure
if cond then expr1 else expr2
⚠️
expr1
andexpr2
have to be the same type.cond
is abool
For exemple
# if 1<2 then "higher" else "lower" ;;
-: string = "higher"
Exercise : absolute program
# let abs(x) =
if x>0 then x
else -x ;;;
val abs : int -> int <fun>
3.2. Exceptions
Division by 0:
# 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
# failwith;;
-: string -> a = <fun>
# 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
# 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 = <fun>
3.3. Filtering
Explicit filtering
Explicit means that you matches the value
General syntax
match expr with pattern1 -> result1 | pattern2 -> result2 | ... | patternn -> resultn
All expressions and pattern must avec the same type
Example
# let f x = match x with
0 -> 18
| 1 -> 24
| y -> y * y;;
val f : int -> int = <fun>
# f 1;;
- : int = 24
# let g x = match x with
0 -> 18
| y -> y + y (*here will return a warning : unused case*)
| 1 -> 24 ;;
val f : int -> int = <fun>
# f 1;;
- : int = 1
# let d x = match x with
0 -> 18;
| 1 -> 24;;
(* Warning = pattern matching not exhaustive *)
Filtering several values
# let and_ a b =
match a with
true -> (match b with
true -> true
| false -> false)
| false -> false;;
⚠️ If you forgot the parentheses, Caml will belived the two
|false
belong to the same pattern matching
Universal pattern
# let f x = match x with
0 -> 18
| 1 -> 24
| _ -> x*x ;;
"Or" filter
# let f x match x with
0 | 20 -> 18
| 1 | 11 | 12 -> 24
|_ -> x * x ;;
Guarded filters
# let sign x = match x with
0 -> 0
| y when y < 0 -> -1
| _ -> 1
y when y<0
is an evaluation
Filtering and anonymous functions
# let succ x = x +1;;
val succ: int -> int = <fun>
# let succ = function x -> x + 1;;
val succ: int -> int = <fun>
# let f x = expr (*is equal to *) let f = function x -> expr
⚠️ Learn by heart