-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathannotations-and-matching.fss
More file actions
64 lines (52 loc) · 1.91 KB
/
annotations-and-matching.fss
File metadata and controls
64 lines (52 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
type Address =
{ City: string
Zip: int }
type Contact =
{ Name: string
City: string
Zip: int
Country: string }
let make_address (address: Address) = address
// Exact named annotation.
let describe_named (address: Address) =
$"named: {address.City} ({address.Zip})"
// Inline nominal-by-shape annotation ({ ... }).
// This resolves to the declared Address type.
let describe_nominal_shape (address: { City: string; Zip: int }) =
$"nominal-shape: {address.City} ({address.Zip})"
// Explicit structural annotation ({| ... |}).
// Any record value with at least City/Zip is accepted.
let describe_structural (address: {| City: string; Zip: int |}) =
$"structural: {address.City} ({address.Zip})"
// Return type annotation on let function.
let city_line (address: Address) : string =
$"{address.City} ({address.Zip})"
// Return type annotation + recursion.
let rec countdown n : string =
if n <= 0 then "done"
else $"tick {n} -> {countdown (n - 1)}"
let office = make_address { City = "London"; Zip = 12345 }
let home = {| City = "Paris"; Zip = 75000 |}
let home = {| home with Name = "Robert" |}
let contact = { Name = "Ada"; City = "Paris"; Zip = 75000; Country = "FR" }
// Cross-calls between helpers.
print (describe_named office)
print (describe_nominal_shape office)
print (describe_nominal_shape (make_address home))
print (describe_structural office)
print (describe_structural home)
print (describe_structural contact)
print (city_line office)
print (countdown 3)
let match_nominal_shape value =
match value with
| { City: string; Zip: int } -> "match nominal shape"
| _ -> "no nominal match"
let match_structural value =
match value with
| {| City: string; Zip: int |} -> "match structural"
| _ -> "no structural match"
print (match_nominal_shape office)
print (match_nominal_shape contact)
print (match_structural office)
print (match_structural contact)