A program is a sequence of expressions that are evaluated one after another.
So far we have seen:
let
expressions and conditionalslet f (b,s) = if b then s else ""
The (a,b)
operation constructs a tuple.
Suppose we want to access the first element of a tuple:
Each match clause has the form pattern -> body
:
Patterns can be constants, names, wild card _
, or constructed from patterns.
How did the definition let pow (b,n) = ...
work?
let f arg = body
≡
let f = fun arg -> body
arg -> body
match clause
When a pattern has multiple possibilities we can bind a name to the expression with as
:
Note: match
statements (and the function...
shorthand) use the first matching pattern:
We can use patterns to combine multiple checks succinctly, e.g.:
Patterns can also be used anywhere a name might be bound:
let (x,y) = (2, "dos") in y
let (x,_) = (4, print_string "Hello!\n")
let f (0|1 as b) = 1-b
let (0 | 1 | 2) = read_int () in 42
What happens if we evaluate:
match "anystring" with 0 -> 1 | _ -> 2
?(function 0 -> true | _ -> false) 1.0
?function 0 -> 'a' | 1 -> "b" | n -> n+1
?function 0 -> 0 | "abracadabra" -> 0 | _ -> 1
?In the expression match e with p1 -> e1 | ... | pk -> ek
:
e
and patterns p1
…pk
must all have “compatible” types;e1
…ek
so the types of e1
…ek
must be the same.Suppose we compile the following definition:
let first_of_triple (x,_,_) = x
What type will it have?
val first_of_triple : 'a * 'b * 'c -> 'a = <fun>
'a
, 'b
, and so on are type variables that can match any type, so
first_of_triple (1,"uno",1.0) : int
first_of_triple ("person","woman","man...") : string
Types involving type variables are called polymorphic.
cs2041.org