Title: Type Variables in ML
1Type Variables in ML
- Until we know the type of a value (perhaps
never!), we use a variable for its type - Book uses, e.g., t1, tx, tf
- PL literature uses Greek letters
- l x.x a ? a
- (lambda (a b) b) ab ? b
- ML uses 'a, 'b, 'c, ...
-
gt fun foo(a,b) b val foo fn 'a 'b -gt 'b
2ML Let's Write...
- sum int list -gt int
- member 'a 'a list -gt bool
Recall fun reverse(nil) nil
reverse(xt) reverse(t) _at_ x
3ML Local environments using let
- Recall (?) mergesort Divide-and-conquer for
sorting a list - Split list into two sorted sublists, then merge
them merge(1,3,5, 2,4,6) 1,2,3,4,5,6 - So first write merge
-
4ML Local environments using let
gt fun merge(nil,M) M merge(L,nil)
L merge(xxs, yys) if (xint) lt
y then xmerge(xs,yys) else
ymerge(xxs,ys) val merge fn int list
int list -gt int list gt merge(1,3,5,
2,4,6) val it 1,2,3,4,5,6 int
list
Now write split
5gt fun split(nil) (nil,nil) split(a)
(a, nil) split(abcs) let
val (M,N) split(cs) in (aM,
bN) end val split fn 'a list -gt 'a
list 'a list gt split(1,2,3,4,5) val it
(1,3,5,2,4) int list int list
Finally write mergeSort
6gt fun mergeSort(nil) nil mergeSort(a)
a mergeSort(L) let val (M,N)
split(L) val M mergeSort(M) val
N mergeSort(N) in merge(M,N) end
val mergeSort fn int list -gt int list gt
mergeSort(5,4,3,2,1) val it 1,2,3,4,5
int list
7ML Polymorphism
- Note that merge is the only function here
explicitly declaring a type (int)
fun merge(nil,M) M merge(L,nil)
L merge(xxs, yys) if (xint) lt
y then xmerge(xs,yys) else
ymerge(xxs,ys)
- We can factor out the int comparison, and make
merge and mergeSort polymorphic
8ML Polymorphism
gt fun merge(nil,M,C) M ( C is comparator fun
) merge(L,nil,C) L merge(xxs,
yys,C) if C (x,y) then
xmerge(xs,yys,C) else
ymerge(xxs,ys,C) val merge fn 'a list
'a list ('a 'a -gt bool)
-gt 'a list
9ML Polymorphism
gt fun mergeSort(nil,C) nil
mergeSort(a,C) a mergeSort(L,C)
let val (M,N) split(L) val M
mergeSort(M,C) val N mergeSort(N,C)
in merge(M,N,C) end val mergeSort fn
'a list ('a 'a -gt bool)
-gt 'a list
10ML Polymorphism
gt fun intcmp(aint, b) a lt b val intcmp fn
int int -gt bool gt fun realcmp(areal, b) a
lt b val realcmp fn real real -gt bool gt
mergeSort(5,4,3,2,1, intcmp) val it
1,2,3,4,5 int list gt mergeSort(5.5, 4.4,
3.3, 2.2, 1.1, realcmp) val it
1.1,2.2,3.3,4.4,5.5 real list
11ML Polymorphism
- Q. What's the point?
- A. ML supports functions as first -class
objects (as in Scheme), while also providing
strong type-checking (as in Java) - Java supports this ability (abstract comparison)
through the Comparable interface.