Pattern Matching in OCaml Flashcards

1
Q

To access the various components of data structures, OCaml uses this powerful feature to divide the process into various branches or cases

A

Pattern matching

let rec sum lst =
match lst with
| [] -> 0
| h::t -> h + sum t ;;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

The underscore symbol that matches anything

A

Wildcard

let xor p =
match p with
| (true, false) -> true
| (false, true) -> true
| _ -> false ;;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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

A

Tail recursion

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

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

A

Tail call optimization

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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>

A

“our default: hello”

“bar is the one”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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 = ?????
A

true

false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly