-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathml3.sml
119 lines (72 loc) · 1.52 KB
/
ml3.sml
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
(* More Pattern Matching *)
(* Case Expressions *)
case 1 + 1 of
3 => "three" |
2 => "two" |
_ => "hmm";
(* Another example *)
val x = 1::2::3;
case x of
_::_::c::_ => c |
_::b::_ => b |
a::_ => a |
nil => 0;
(* Predefined Functions *)
ord;
~;
(* Defining Functions *)
val x = ~;
x 3;
(* Anonymous Functions *)
fun f x = x + 2;
f 1;
(* Anonymous Function *)
fn x => x + 2;
(fn x => x + 2) 1;
(* Equivalent Effects *)
fun f x = x + 2;
val f = fn x => x + 2;
(* The op Keyword *)
op *;
(* Currrying *)
fun f (a, b) = a + b;
fun g a = fn b => a + b;
f (2, 3);
g 2 3;
val add2 = g 2;
add2 3;
add2 10;
(* Multiple Curried Parameters *)
fun f (a, b, c) = a + b + c;
fun g a = fn b => fn c => a + b + c
f (1, 2, 3);
g 1 2 3;
(* Easier notation for currying *)
fun f a b c d = a + b + c + d;
(* The map function *)
map ~ [1, 2, 3, 4];
map (fn x => x + 1) [1, 2, 3, 4];
map (fn x => x mod 2 = 0) [1, 2, 3, 4];
map (op +) [(1, 2), (3, 4), (5, 6)];
map;
val f = map (op +);
f [(1, 2), (3, 4)];
(* The foldr function *)
foldr (op +) 0 [1, 2, 3, 4];
foldr (op * ) 1 [1, 2, 3, 4];
foldr (op ^) "" ["abc", "def", "ghi"];
foldr (op ::) [5] [1, 2, 3, 4];
(* foldr is curried *)
foldr;
foldr (op +);
foldr (op +) 0;
val addup = foldr (op +) 0;
addup [1,2,3,4,5];
(* The foldl function *)
foldl (op +) 0 [1, 2, 3, 4];
foldl (op * ) 1 [1, 2, 3, 4];
(* foldl vs foldr *)
foldr (op ^) "" ["abc", "def", "ghi"];
foldl (op ^) "" ["abc", "def", "ghi"];
foldr (op -) 0 [1, 2, 3, 4];
foldl (op -) 0 [1, 2, 3, 4];