100 likes | 257 Views
ML: A Strongly Typed Functional Language. Interpreted (compilers available): -bash-3.00$ poly Poly/ML 5.4 Release > 1+3; val it = 4 : int > o ^D -bash-3.00. ML: A Strongly Typed Functional Language. Strongly typed: > 1.5 + 3; Error-Type error in function application.
E N D
ML: A Strongly Typed Functional Language Interpreted (compilers available): -bash-3.00$ poly Poly/ML 5.4 Release > 1+3; val it = 4 : int >o^D -bash-3.00
ML: A Strongly Typed Functional Language Strongly typed: > 1.5 + 3; Error-Type error in function application. Function: + : real * real -> real Argument: (1.5, 3) : real * int Reason: Can't unify int (*In Basis*) with real (*In Basis*) (Different type constructors) Found near 1.5 + 3 Static Errors
ML: A Strongly Typed Functional Language Functional: > fun square(x:int) = x*x; val square = fn : int -> int > map square [1,2,3]; val it = [1,4,9] : int list
ML: A Strongly Typed Functional Language Type-inferencing: > fun add(x:int, y) = x+y; val add = fn : int * int -> int > fun foo(a, b, c) = if a then b else 1+c; val foo = fn : bool * int * int -> int
ML: A Strongly Typed Functional Language Pattern-matching: > fun fact(n) = if n = 0 then 1 else n * fact(n-1); val fact = fn : int -> int > fact(5); val it = 120 : int > fun fact(0) = 1 | fact(n) = n * fact(n-1); val fact = fn : int -> int > fact(5); val it = 120 : int
ML: Lists > val a =[1,3,5,7,9]; val a = [1,3,5,7,9] : int list > hd(a); val it = 1 : int > tl(a); val it = [3,5,7,9] : int list > a @ [11]; val it = [1,3,5,7,9,11] : int list
ML: Lists > fun rev(ls) = if null(ls) then nil else rev(tl(ls)) @ [hd(ls)]; val rev = fn : 'a list -> 'a list > rev([1,3,5,7,9]); val it = [9,7,5,3,1] : int list > > fun rev(nil) = nil | rev(x::t) = rev(t) @ [x]; val rev = fn : 'a list -> 'a list > rev([1,3,5,7,9]); val it = [9,7,5,3,1] : int list
ML: Tuples (single, double, triple, quadruple, quintuple, sextuple, heptuple, octuple, ..., -tuple): > [1,2,3]; val it = [1,2,3] : int list > (1,2,3); val it = (1,2,3) : int * int * int > [1,2,3.5]; Error-Elements in a list have different types. > (1,2,3.5); val it = (1,2,3.5) : int * int * real
So f(3,4) is a fun of one arg: tuple of type • int*int • Recall imaginary numbers / complex arithmetic: • C = {ai + b}, i = √-1 • So can represent C as real*real: • - fun cmag (a, b) = sqrt(a*a + b*b); • val cmag = fn : real * real -> real % how inferred? • - cmag (3.0, 4.0); • val it = 5.0 : real ML: Tuples
ML: Tuples - fun cadd(a1:real, b1:real) (a2, b2) = (a1+a2, b1+b2); val cadd = fn : real * real -> real * real -> real * real - cadd (3.3, 4.4) (5.5, 6.6); val it = (8.8,11.0) : real * real - fun cadd (a1,b1) (a2,b2) = (a1+a2,b1+b2):real*real; val cadd = fn : real * real -> real * real -> real * real