Title: A First Look at ML
1A First Look at ML
Download as Power Point file for saving or
printing.
Download as Power Point file for saving or
printing.
- Additional information
- Programming in ML
- A Gentle Introduction to ML
2Why ML?
- Very high level above machine architecture
powerful - Functional language everything returns a result
- Interactive code and test immediately
- Minimal side effects - easier to reason about
program behavior - Native list operations
- Pattern matching programming style
- Useful for studying fundamentals of languages
- Used to implement language interpreter
3Functional Languages
- Example a factorial function in ML
- Hallmarks of functional languages
- Single-valued variables
- Heavy use of recursion
- Functions are first-class citizens, can be used
as parameters, function results, etc. - Minimal use of assignments and side-effects
fun fact x if x lt 0 then 1 else x
fact(x-1)
4ML
- Meta Language
- One of the more popular functional languages
along with Lisp and Scheme - Useful in Artificial Intelligence and programming
languages. - Edinburgh, 1974, Robin Milners group
- There are a number of dialects
- We are using Standard ML, but we will just call
it ML from now on
5Using ML at IUS
- Start Programs Student Apps
- Network Shortcuts Poly ML
- Enter ML instructions
6Using ML at Home
-
- Unzip and run the Setup
- Open by something similar to
- Start Programs Poly ML
- Run Poly ML
- Enter ML instructions
7Programming, Copying and Pasting
- Program ML by
- Entering instructions at the gt prompt in the
execution window for immediate execution. - Enter instructions in Notepad or in ML source
editor. Copy and paste into execution window. - Copy from these notes and paste into Poly ML
execution window. - Use the Edit Paste or Ctrl V
- Poly ML ignores input when using right-click Paste
8Example 123
gt 123 val it 7 intgt 123 val it
7 int
- Type an expression after gt prompt ML replies
with value and type - After the expression put a . (The is not part
of the expression.) - If you forget, the next prompt will be ( in
some ML), meaning that ML expects more input,
then type the ). - Variable it is a special variable bound to
expression value typed.
9Outline
- Constants
- Operators
- Defining Variables
- Tuples and Lists
- Defining Functions
- ML Types and Type Annotations
10Number constants
1234 val it 1234 int123.4 val it
123.4 real
- Integer constants standard decimal , but use
tilde for unary negation (such as 1) - Real constants standard decimal notation
- Note the type names int, real
11bool constants
true val it true boolfalse val it
false bool
- Boolean constants true and false
- ML is case-sensitive use true, not True or TRUE
- Note type name bool
12char and string constants
"fred" val it "fred" string"H" val it
"H" string"H" val it "H" char
- String constants text inside double quotes
- Can use C-style escapes \n, \t, \\, \", etc.
- Character constants put before a 1-character
string - Note type names string and char
13Outline
- Constants
- Operators
- Defining Variables
- Tuples and Lists
- Defining Functions
- ML Types and Type Annotations
14Arithmetic
1 2 - 3 4 div 5 mod 6 val it 1
int 1.0 2.0 - 3.0 4.0 / 5.0 val it
1.4 real
- Standard operators for integers, using for
unary negationand - for binary subtraction - Same operators for reals, but use / for division
- Left associative, precedence is ,- lt
,/,div,mod lt .
15Concatenation and Relations
"bibity" "bobity" "boo" val it
"bibitybobityboo" string 2 lt 3 val it true
bool1.0 lt 1.0 val it true bool"d" gt
"c" val it true bool"abce" gt "abd"
val it false bool
- String concatenation operator
- Ordering comparisons lt, gt, lt, gt, apply to
string, char, int and real - Order on strings and characters is lexicographic
(alphabetic)
16More Relations
1 2 val it false bool true ltgt false
val it true bool 1.3 1.3 Error operator
and operand don't agree equality
type required operator domain ''Z ''Z
operand real real in expression
1.3 1.3
- Equality comparisons and ltgt
- Most types are equality testable these are
equality types - Type real is not an equality type
17bool operators
1 lt 2 orelse 3 gt 4 val it true bool1 lt 2
andalso not (3 lt 4) val it false bool
- Boolean operators andalso, orelse, not. (And we
can also use for equivalence and ltgt for
exclusive or.) - Precedence so far orelse lt andalso lt
,ltgt,lt,gt,lt,gt lt ,-, lt ,/,div,mod lt
,not
18Short-circuiting bool operations
true orelse 1 div 0 0 val it true bool
- Note andalso and orelse are short-circuiting
operators if the first operand of orelse is
true, the second is not evaluated likewise if
the first operand of andalso is false. - Technically, they are not ML operators, but
keywords. - All true ML operators evaluate all operands.
23 lt 5 val it false bool
19Conditionals
if 1 lt 2 then " 1 lt 2" else "2 lt 1" val it "
1 lt 2" stringif 1 gt 2 then 34 else 56 val
it 56 int(if 1 lt 2 then 34 else 56) 1
val it 35 int
- Value of the expression is the value of the then
part if the test part is true or the value of the
else part otherwise - Similar to C's ternary operator (1lt2) ? 'x'
'y' - Conditional expression (not statement) using if
then else - No if then construct
if 1 lt 2 then 3 Error else expected but was
found
20Exercise 1
- What is the value and ML type for each of these
expressions? - "abc" "def" gh"
- if (1 lt 2) then 3.0 else 4.0
- 5 (if (1 lt 2) then 3 else 4)
- 1 lt 2 orelse (1 div 0) 0
- What is wrong with each of these expressions?
- 10 / 5
- "a" "b" or 1 2
- 1.0 1.0
- if 1.0 lt 2.0 then 3
21No Implicit type conversion
1 2 val it 2 int1.0 2.0 val it
2.0 real1.0 2 Error operator and operand
don't agree 1.0 lt 2 Error Can't unify int
with real (Different type constructors)
- The , , lt and other integer operators are
overloaded to have one meaning on pairs of
integers, and another on pairs of reals. - ML does not perform implicit type conversion.
22Explicit type conversion
real 123 val it 123.0 realfloor 3.6
val it 3 intfloor 3.6 lt 4 val it true
boolstr "a" val it "a" string
- Builtin conversion functions real (int to real),
floor (real to int), ceil (real to int), round
(real to int), trunc (real to int), ord (char to
int), chr (int to char), str (char to string) - Apply a function to the argument by function
argument. - For example floor 3.6
23Function Associativity
- Function application is left-associative
- So f a b means (f a) b, which means
- first apply f to the single argument a
- then take the value f returns, which should be
another function - then apply that function to b
- For example, chr trunc 97.5 should be written as
- chr (trunc 97.5)
- More on how this can be useful later
24Function application precedence
square 21 val it 5 int square (21)
val it 9 int
- Function application has higher precedence than
any operator. - Parenthesize to define an explicit precedence.
25Exercise 2
- What, if anything, is wrong with each of these
expressions? - trunc 5
- ord "a" 1
- 54.0
- if 0 then 1 else 2
- if true then 1 else 2.0
- chr(trunc(97.0))
- chr(trunc 97.0)
- chr trunc 97.0
26Outline
- Constants
- Operators
- Defining Variables
- Tuples and Lists
- Defining Functions
- ML Types and Type Annotations
27Variable definition
val x 123 val x 7 intx val it 7
intval y if x 7 then 1.0 else 2.0 val y
1.0 real
- Define a new variable and bind to a value using
val. - Variable names should consist of a letter,
followed by zero or more letters, digits, and/or
underscores.
28Multiple Variable Definitions
val fred 23 val fred 23 intval fred
true val fred true boolfred val it
true bool
- Can define a new variable with the same name as
an old one, even using a different type. (This
is not particularly useful.) - This is not the same as assignment. It defines a
new variable but does not change the old one.
Any part of the program that was using the first
definition of fred, still is after the second
definition is made.
29Exercise 3
Suppose we make these ML declarations val a
"123"val b "456"val c a b "789"val
a 3 4 Then what is the value and type of
each of these expressions? 1) a2) b3) c4) a
6
30The Inside Story
- In interactive mode, the expected input is a
sequence of declarations - If you type just an expression exp instead of a
declaration, ML treats it as if you had typed
val it exp - For example
5 val it 5 int
31Garbage Collection
- Sometimes the ML interpreter will print a line
like this, for no apparent reason GC
0.0.0.0.1.3 (0 ms) - This is what ML says when it is performing a
garbage collection reclaiming pieces of memory
that are no longer being used - Well see much more about this when we look at
Java.
32Outline
- Constants
- Operators
- Defining Variables
- Tuples and Lists
- Defining Functions
- ML Types and Type Annotations
33Tuples
val barney (12, 3.04.0, "brown") val
barney (3,12.0,"brown") intrealstringval
point1 ("red", (300,200)) val point1
("red",(300,200))string(intint) 2 barney
val it 12.0 real1 (2 point1) val it
300 int
Heterogeneous, tuples can contain other tuples
(i.e. mixed types) Parentheses define tuples A
tuple is similar to a struct in C but with no
field names i x is the i'th element of tuple x.
For example 2 (red,50, true) is 50
34No tuple of one
(1, 2) val it (1,2) int int (1) val
it 1 int 1 (1, 2) val it 1 int 1
(1) Error operator and operand don't agree
operator domain 1'Y 'Z operand
int in expression (fn 11,... gt 1) 1
There is no such thing as a tuple of one
35Tuple Type Constructor
- The type of a tuple gives as a type
constructor - For tuple (5,true) int bool is the type of
pairs ( x, y ) where x is an int and y is a bool - Parentheses have structural significance, each
below are different - int (int bool) (5,(6, true))
- (int int) string ((5,6), Hi)
- int int bool (5, 6, true)
- (boolint)(intreal) ((true,4),(5,3.1))
36Exercise 4
- What are the values of these expressions?
- 2 (3,4,5)
- val x (12, 3.00.5, "zig" "zag")
- 3 x
- (4,5) (4,5)
- What is wrong with the following expressions?
- 4 (3,4,5)
- (4, "zig") (4,5)
- (4,5.0) (4,5.0)
- What is the type?
- (3,"zig",5.3)
- (3,(4, "zig"),5.3)
37Lists
1,2,3 val it 1,2,3 int
list1.0,2.0 val it 1.0,2.0 real
listtrue val it true bool
list (1,2),(1,3) val it (1,2),(1,3)
(int int) list1,2,3,1,2 val it
1,2,3,1,2 int list list
- Square brackets define lists.
- Homogenous, all list elements must be the same
type. - 1.0,2.0 real list
- (1,2.0),(1,3.2) (int real) list
38Empty list
val it 'a listnil val it
'a list nil val it true bool
Empty list is or nil Note the type of the
empty list 'a list Any variable name beginning
with an apostrophe is a type variable it stands
for a type that is unknown 'a list means a list
of elements, type unknown
39The null test
null val it true boolnull 1,2,3
val it false bool
- null tests for the empty list
- Can use an equality test, as in x
- However, null x is preferred we will see why in
a moment
40List Type Constructor
- The type list is type constructor
- For example 5,6 the type int list means each
element is of type int - A list is not a tuple 5,6 is not (5,6)
41_at_ concatenates lists
1,2,3_at_4,5,6 val it 1,2,3,4,5,6 int
list
_at_ operator concatenates two lists of the same
type 5 _at_ 6,7 result is 5, 6, 7 5 _at_ 6,
7 Error, both must be lists true _at_ 6,
7 Error, lists must be same type (2,"Hel")_at_(3
, "lo") (2, "Hel"), (3, lo") (2,"Hel")_at_(3
, 5) Error, lists not same type
42 builds lists
val n 56,7 val it 5, 6, 7 int
list val x 5 val x 5 int
list val y 6x val y 6,5 int
listval z 7y val z 7,6,5 int list
operator is List-builder (pronounced cons)
Constructs new list by appending element to a
list operator is right-associative 567
result is 5, 6, 7
43hd and tl access list head and tail
val z 12 val z 1,2 int list hd
z val it 1 int tl z val it 2 int
listtl(tl z) val it int list
The hd function returns the head of a list the
first element hd 5, 6, 7 returns 5 The tl
function returns the list tail all but the first
element tl 5, 6, 7 returns 6, 7
44Strings explode and implode
explode "hello" val it "h","e","l","l",
"o" char listimplode "h","i" val it
"hi" string
explode function converts a string to a list of
characters. implode function does the reverse
converts a list of characters to a string.
45Exercise 5
- What are the values of these expressions?
- 1,2_at_3,4
- 12
- 12nil
- hd(12nil)
- hd 1,2,3,4
- tl 1,2,3,4
- tl 5
- hd(tl(2(1,2,3,4)))
- hd (3,4),(5,6)
- (hd 1,3,4)2(tl 1,3,4)
46Exercise 5 Continued
- What is wrong with the following expressions?
- hd
- hd(tl(tl 1,2))
- 1_at_2
- 12,3
- hd 12nil
47Exercise 5 Continued
- Give ML to yield the result
- Concatenate 1,2 with 3,4.
- 1 consed to 2,3.
- Second element of 1,2,3,4.
- Last element of 1,2,3,4.
- 2 consed to 1,3 to yield 1,2,3.
- Hint Use 2 statements.
48Outline
- Constants
- Operators
- Defining Variables
- Tuples and Lists
- Defining Functions
- ML Types and Type Annotations
49Function definition
fun add (x, y) x y val add fn int
int -gt int
- add the function name
- (x, y) parameter tuple
- x y function result
- val addfn int int -gt int Function type
Analogous C example
int add(int x, int y) return x y
50fun function definition
fun firstChar str hd (explode str) val
firstChar fn string -gt char firstChar
"abc" val it "a" char
fun defines a new function and binds to variable
firstChar Type fn means a function. firstChar is
a string -gt char function whose argument str type
is string and the return type is char Rarely
necessary to declare any types, since ML infers
them. ML determines that str is a string from
explode str.And the function result must be a
char from hd (explode str) since result is the hd
of a char list
51Function Definition Syntax
ltfun-defgt fun ltfunction-namegt
ltparametergt ltexpressiongt
- ltfunction-namegt can be any legal ML name
- The simplest ltparametergt is just a single
variable name the formal parameter of the
function - The ltexpressiongt is any ML expression its value
is the value the function returns - This is a subset of ML function definition
syntax more in Chapter 7
52Function Type Constructor
- ML gives the type of functions using -gt as a type
constructor - For example, int -gt real is the type of a
function that takes an int parameter (the domain
type) and produces a real result (the range type) - From math, a function maps domain values to range
values. - fun f x x mod 4 maps the domain of integers
to the range of 0..3. - The type is val f fn int -gt int
53Parameter passing
fun quot(a,b) a div b val quot fn int
int -gt int quot (6,2) val it 3 int val
pair (6,2) val pair (6,2) int
int quot pair val it 3 int quot (6,
2.0) ErrorCan't unify int with real
All ML functions take exactly one parameter Can
pass more than one element as a tuple quot
(6,2)
54Function parameter and return types
- fun cons (a,L) aLval cons fn 'a 'a
list -gt 'a list
Function name consParameter tuple - a a
list Element one type unknown a Element two
list type unknown - a listResult list type
unknown a list
55Exercise 5.5
- What are the results for the following?
- fun fa x x 1 fa 3
- fun fb (x, y) x fb (1, 2, 3, 4) fb (3,
4) - fun fc x tl x fc 1, 2, 3
- fun fd (x, y) hd x tl y fd (1, 2, 3,
4, 5, 6) - fun fe x hd x 1 fe 3, 2, 1
56Exercise 5.5 Continued
- What are the parameter and return types?
- fun fa x x 1
- fun fb (x, y) x
- fun fc x tl x
- fun fd (x, y) hd x tl y
- fun fe x hd x 1
57Recursion
- Functional languages are characterized by use of
recursion for repetition - Functional languages such as ML minimize
assignment hazard of side effects - Repetition (e.g. for, while, do while, etc.)
requires assignment, for example - for(i0 ilt10 ii1) cout ltlt i
58Recursive factorial function
fun fact n if n 0 then 1 else n
fact(n-1) val fact fn int -gt int fact 5
val it 120 int
- Many recursive functions consist of a pattern of
two steps - Test for base case, terminating condition
- if n 0 then 1
- Recurse, moving closer to terminating condition.
- else n fact(n-1)
59Exercise 5.6
- Write the recursive functions
- Sum 3 val it 6 int
- Fib(10) val it 55int Fib( int n ) if (
n lt 1 ) return n else return Fib(n-1)
Fib(n-2) - interest(0.06, 1000.0, 5) val it 1338.225578
realfloat interest(rate, principle, year)
if (year 0) return principle else return
interest(rate,(1.0rate)principle, year-1)
60Recursive int list summation
fun summation x if null x then 0 else hd
x summation(tl x) val summation fn int
list -gt int summation 1,2,3,4,5 val it 15
int
- Common recursive function pattern for list
arguments - base case test for null list if
null x then 0 - recursive call moving closer to base case of
null x summation (tl x)
61Recursive list length
fun length x if null x then 0 else 1
length (tl x) val length fn 'a list -gt
intlength true,false,true val it 3
intlength 4.0,3.0,2.0,1.0 val it 4 int
Recursive function to compute the list length is
predefined in ML. Note type fn 'a list -gt int
works on any type of list. It is polymorphic
while summation operates on int lists only.
62null vs
fun badlength x if x then 0 else 1
badlength (tl x) val badlength fn ''a list
-gt intbadlength true,false,true val it 3
intbadlength 4.0,3.0,2.0,1.0 Error
operator and operand don't agree equality type
required
Same as previous example, but with x instead
of null x Type variables with two apostrophes,
''a, are restricted to equality types. Error due
to x, real values in list x not equality
type. Use null x instead of x. It avoids
unnecessary type restrictions.
63Recursive last element in list
fun last L if null (tl L) then hd L else
last (tl L) val last fn 'a list -gt
'a last 1,2,3 val it 3 int
- Notice recursion pattern of
- test for base case null (tl L), return base case
value hd L one element remaining in L - recurse last(tl L), moving closer to base case
64Recursive all but last element in list
fun allbutlast L if null (tl L) then
else hd L allbutlast (tl L) val allbutlast
fn 'a list -gt 'a list allbutlast 1,2,3
val it 1, 2 int list
- Notice recursion pattern of
- test for base case null (tl L), return base case
value - recurse allbutlast(tl L), moving closer to base
case
65Recursive nth element in list
fun Nth (n, L) if n 1 then hd L else
Nth (n-1, tl L) val Nth fn int 'a list
-gt 'a Nth (2, true,false,true)val it
false bool Nth (2, ("a", 4), ("b", 2)
) val it ("b", 2) string int
Type fn int 'a list -gt a works on any type
of list, polymorphic on the list parameter. Fails
when list has less than n elements.
66Recursive list identity
fun identity L if null L then else hd
L identity (tl L) val identity fn 'a
list -gt 'a list identity 1,2,3 val it 1,
2, 3 int list
- Notice recursion pattern of
- test for base case null L, return base case value
- recurse identity(tl L), moving closer to base case
67Recursive list reverse
fun reverse L if null L then nil else
reverse(tl L) _at_ hd Lval reverse fn 'a
list -gt 'a list reverse 1,2,3val it
3,2,1 int list
- Notice recursion pattern of
- test for base case null L, return base case value
- recurse reverse(tl L), moving closer to base case
68Exercise 6
How does ML determine that function summation
returns int? fun summation x if null x
then 0 else hd x summation(tl x)
- What are the values of these expressions?
- fun addInt (a, b) abaddInt 3 4
- fun cons(a,b) a bcons("hello","world")
- fun dubal L if null L then else 2(hd
L)dubal(tl L)dubal 1,2,3
69Exercise 6 Continued
What are the results of these expressions?
- fun rac s if null (tl s) then hd
s else rac (tl s)rac 1,2,3 - fun rdc L if null (tl L) then
else (hd L)rdc(tl L)rdc
1,2,3,4 - fun R L if null L then L else
(rac L) R (rdc L)R 1,2,3
70Exercise 6 Continued
- Write the functions that return the following
results - inc 4 returns 5
- second "hello","world" returns "worldsecond
4, 5, 3 returns 5 - firstAbove0 4, 0, 5, 2 returns 5
- smallest 5, 4, 3 returns 4
- snoc (3, 4,5) returns 4, 5, 3
- member(4, 3,4,5) returns truemember(4, 3,
5) returns false
71Outline
- Constants
- Operators
- Defining Variables
- Tuples and Lists
- Defining Functions
- ML Types and Type Annotations
72ML Types So Far
- So far we have the primitive ML types int, real,
bool, char, and string - Also we have three type constructors
- Tuple types using
- List types using list
- Function types using -gt
73Combining Constructors
- When combining constructors, list has higher
precedence than , and -gt has lower precedence - int bool list same as int (bool list)
- int bool list -gt real same as(int (bool
list)) -gt real - Use parentheses as necessary for clarity
74Parameter typing
fun prod(a,b) a b val prod fn int
int -gt int
Why int rather than real? MLs default type for
(and and ) is int int int -gt int You can
give an explicit type annotation to get real
instead
75Type annotation
gt fun prod(areal,breal)real abval prod
fn real real -gt real
Type annotation is a colon followed by a type Can
appear after any variable or expression These are
all equivalent fun prod(a,b)real a bfun
prod(areal,b) a bfun prod(a,breal) a
bfun prod(a,b) (areal) bfun prod(a,b)
a brealfun prod(a,b) (ab)realfun
prod((a,b)real real) ab
76Summary
- Constants and primitive types int, real, bool,
char, string - Operators , , -, , div, mod, /, , , _at_, lt,
gt, lt, gt, , ltgt, not, andalso, orelse - Conditional expression
- Function application
- Predefined functions real, floor, ceil, round,
trunc, ord, chr, str, hd, tl, explode, implode,
and null
77Summary, Continued
- Defining new variable bindings using val
- Tuple construction using (x,y,,z) and selection
using n - List construction using x,y,,z
- Type constructors , list, and -gt
- Function declaration using fun, including tuple
arguments, polymorphic functions, and recursion - Type annotations