Pattern Matching in OCaml Flashcards
To access the various components of data structures, OCaml uses this powerful feature to divide the process into various branches or cases
Pattern matching
let rec sum lst =
match lst with
| [] -> 0
| h::t -> h + sum t ;;
The underscore symbol that matches anything
Wildcard
let xor p =
match p with
| (true, false) -> true
| (false, true) -> true
| _ -> false ;;
Recursive function that does not perform any computation after the recursive call returns, and immediately returns to its caller the value of its recursive call
Tail recursion
Recursion leads to a call stack. Instead of growing this, the caller’s stack frame is simply replaced with that of the called function. What is this called
Tail call optimization
What is the output?
let f x =
match x with
“foo” -> “it is foo”
| “bar” -> “bar is the one”
| “zap” -> “totally different”
| _ -> “our default: “ ^ x
;;
val f : string -> string = <fun>
# f "hello";;
- : string = ?????
# f "bar";;
- : string = ?????</fun>
“our default: hello”
“bar is the one”
What is the output?
# let rec mem x list = match list with [] -> false | hd::tl -> hd = x || mem x tl ;; val mem : 'a -> 'a list -> bool = <fun> # mem 3 [1;2;3;4;5];; - : bool = ????? # mem 12 [1;2;3;4;5];; - : bool = ?????
true
false