COMP0020-2020-lecture16-ProgrammingExamples With Captions
COMP0020-2020-lecture16-ProgrammingExamples With Captions
Christopher D. Clack
2020
Lecture 16
PROGRAMMING EXAMPLES
CONTENTS
• Grammar provided:
exp :: const | exp op exp | ‘(‘ exp ‘)’
op :: ‘*’ | ‘+’ | ‘-’| ‘/’
const :: digit | digit const
digit :: ‘1’| ‘2’| ‘3’| ‘4’| ‘5’| ‘6’| ‘7’| ‘8’| ‘9’| ‘0’
• Algebraic types:
• Test values:
||(4) ∗ 5
test1 = App (Bracketed (Constant 4)) Times (Constant 5)
||(4 + 5)∗(3−2)
test2 = App
(Bracketed (App (Constant 4) Plus (Constant 5)))
Times
(Bracketed (App (Constant 3) Minus (Constant 2)))
A GAME OF SOLITAIRE
direction ::= N | S | E | W
board == [[peg]]
initboard :: board
initboard = [[Invalid, Invalid, Peg, Peg, Peg, Invalid, Invalid],
[Invalid, Invalid, Peg, Peg, Peg, Invalid, Invalid],
[ Peg, Peg, Peg, Peg, Peg, Peg, Peg],
[ Peg, Peg, Peg, Hole, Peg, Peg, Peg],
[ Peg, Peg, Peg, Peg, Peg, Peg, Peg],
[Invalid, Invalid, Peg, Peg, Peg, Invalid, Invalid],
[Invalid, Invalid, Peg, Peg, Peg, Invalid, Invalid]]
Motivation:
We have already seen how a list can be represented using Now we consider a new representation
using functions that we will call cons and
an algebraic type: nil:
cons 1 (cons 2 (cons 3 nil))
mylist * ::= Nil | Cons * (mylist *) Notice the difference between Cons
with an uppercase C and cons with a
lowercase c: the former is a constructor
Thus, the list value (1 : (2 : (3 : []))) can be represented as: of an algebraic type whereas the latter
will be a function name. The same
observation applies to Nil and nil.
Cons 1 (Cons 2 (Cons 3 Nil))
Consider the following definitions for the two functions or as a partial application of cons to its
first two arguments:
cons and nil: list2 = cons ‘A’ nil
Both list1 and list2 have the same type:
cons a b f = f a b False they are functions that take an
argument function f and return
whatever value is returned by f. The
nil f = f (error “head of nil”) (error “tail of nil”) True function f takes three arguments.
list1 = nil