CS52 - Spring 2017 - Class 11
Example code in this lecture
compose.sml
binTree.sml
Lecture notes
admin
- Midterm 2
- next Thursday
- we will provide summary page of CS52 machine instructions at the end of the manual
- Can additionally bring one page (one side of an 8.5 x 11 piece of paper) of notes
- Topics
- CS52 machine
- assembly code
- memory layout
- stacks
- etc
- number representation (different bases)
- signed binary representation (we'll talk about it next Tuesday), so there will be light coverage
function composition
- In math, if we have two functions:
f(x) = x+2
g(x) = x*x
- what is the composition of those two function (written f o g)?
f(g(x))
- For example, what is (f o g)(2)?
- g(2) = 4
- f(4) = 6
- In SML, we can also compose functions using the composition operator "o" (lowercase o)
- For SML functions f and g, what are the type requirements for us to compose them, f o g?
- f: 'a -> 'b
- g: 'c -> 'a
- and the composition returns a function, of type 'c -> 'b
look at
compose.sml code
- what do the following return?
c1 8
c2 8
c3 8
- 100
- 66
- 100
- what is the type of f o g?
- int -> int (a function!)
Recursive data structures
- See slides
Write a function called sumTree sums the numbers in a tree:
sumTree: int binTree -> int
- How many patterns will we have?
- at least 2, one for each of the constructors of the datatype
fun sumTree Empty = ?
| sumTree (Node (left,v,right)) = ?
- Look at the sumTree function in
binTree.sml code
- Notice that recursive structures lend themselves very nicely to recursive functions
Write a function called maxTree that finds the larges value in a tree:
maxTree: int binTree -> int
ASSUMING:
1) non-negative values in the tree
2) maxTree Empty = -1
- Again, this should follow a very similar structure as sumTree
fun maxTree Empty = ?
| maxTree (Node (left,v,right)) = ?
- Intuitively the max of a tree is either:
1) the value at that node
2) the largest value in the left subtree
3) the largest value in the right subtree
- Just need to get these three things and then compare
- Look at maxTreeSimple function in
binTree.sml code
For those curious, maxTree in
binTree.sml code
uses exceptions and exception handling to remove our assumptions
parsing
- What is parsing?
EBNF syntax
EBNF for numbers:
N ::= [S]D[F]
S ::= + | -
F ::= .D
D ::= {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9}
EBNF syntax
- EBNF = Extended Backus-Naur Form
- | denotes 'or', i.e. pick one of the options
- [] denotes optionally include
- {} denotes include 1 or more repetitions
- Note that each repetition doesn't necessarily have to choose the same options
For example:
- -10
N
SD (N -> SD)
-10
- 15.2
N
DF (N -> DF)
15F (D -> 15)
15.D (F -> .D)
15.2 (D -> 2)
Which of the following are described by the language above?
- +12
- -10.542
- 10.
- +-7