Top Banner
Homework 1 Types and programming languages 1 / 24
25

Types and programming languages - basics.sjtu.edu.cn

Jun 07, 2022

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Types and programming languages - basics.sjtu.edu.cn

Homework 1

Types and programming languages 1 / 24

Page 2: Types and programming languages - basics.sjtu.edu.cn

3.3.43.3 Induction on Terms 31

3.3.4 Theorem [Principles of induction on terms]: Suppose P is a predicate on

terms.

Induction on depth:

If, for each term s,

given P(r) for all r such that depth(r) < depth(s)

we can show P(s),

then P(s) holds for all s.

Induction on size:

If, for each term s,

given P(r) for all r such that size(r) < size(s)

we can show P(s),

then P(s) holds for all s.

Structural induction:

If, for each term s,

given P(r) for all immediate subterms r of s

we can show P(s),

then P(s) holds for all s. �

Proof: Exercise (««). �

Induction on depth or size of terms is analogous to complete induction

on natural numbers (2.4.2). Ordinary structural induction corresponds to the

ordinary natural number induction principle (2.4.1) where the induction step

requires that P(n+ 1) be established from just the assumption P(n).

Like the different styles of natural-number induction, the choice of one

term induction principle over another is determined by which one leads to

a simpler structure for the proof at hand—formally, they are inter-derivable.

For simple proofs, it generally makes little difference whether we argue by

induction on size, depth, or structure. As a matter of style, it is common prac-

tice to use structural induction wherever possible, since it works on terms

directly, avoiding the detour via numbers.

Most proofs by induction on terms have a similar structure. At each step of

the induction, we are given a term t for which we are to show some property

P , assuming that P holds for all subterms (or all smaller terms). We do this

by separately considering each of the possible forms that t could have (true,

false, conditional, 0, etc.), arguing in each case that P must hold for any t of

this form. Since the only parts of this structure that vary from one inductive

proof to another are the details of the arguments for the individual cases, it is

common practice to elide the unvarying parts and write the proof as follows.

Types and programming languages 2 / 24

Page 3: Types and programming languages - basics.sjtu.edu.cn

3.3.4

SolutionDefine

Q(n) = ∀s with depth(s) = n,P(s) holds

Then ”P(s) holds for all s” is equivalent to ”Q(n) holds for all n”

Types and programming languages 3 / 24

Page 4: Types and programming languages - basics.sjtu.edu.cn

3.3.4

If, for each term s,given P(r) for all r such that depth(r) < depth(s)we can show P(s),

then Q(n) holds for all n.

Proof.By induction on natural numbers.

Assume ∀i < n,Q(i) holds

⇒ ∀i < n, ∀r with depth(r) = i ,P(r) holds (by definition of Q(n))⇒ ∀r with depth(r) < n,P(r) holds

⇒ ∀s with depth(s) = n,∀r with depth(r) < depth(s),P(r)holds

⇒ ∀s with depth(s) = n,P(s) holds (by the premise)

⇒ Q(n) holds

Types and programming languages 4 / 24

Page 5: Types and programming languages - basics.sjtu.edu.cn

3.5.10

Rephrase Definition 3.5.9 as a set of inference rules.

The multi-step evaluation relation →∗ is the reflexive, transitiveclosure of one-step evaluation. That is, it is the smallest relationsuch that (1) if t → t ′ then t →∗ t ′, (2) t →∗ t for all t, and (3) ift →∗ t ′ and t ′ →∗ t ′′, then t →∗ t ′′.

Types and programming languages 5 / 24

Page 6: Types and programming languages - basics.sjtu.edu.cn

3.5.10

Solution

494 A Solutions to Selected Exercises

3.5.10 Solution:

t -→ t′

t -→∗ t′

t -→∗ t

t -→∗ t′ t′ -→∗ t′′

t -→∗ t′′

3.5.13 Solution: (1) 3.5.4 and 3.5.11 fail. 3.5.7, 3.5.8, and 3.5.12 remain valid. (2)

Now just 3.5.4 fails; the rest remain valid. The interesting fact in the second

part is that, even though single-step evaluation becomes nondeterministic in

the presence of this rule, the final results of multi-step evaluation are still

deterministic: all roads lead to Rome. Indeed, a rigorous proof of this fact is

not very hard, though it is not as trivial as before. The main observation is

that the single-step evaluation relation has the so-called diamond property:

A.1 Lemma [Diamond Property]: If r -→ s and r -→ t, with s ≠ t, then there is

some term u such that s -→ u and t -→ u. �

Proof: From the evaluation rules, it is clear that this situation can arise only

when r has the form if r1 then r2 else r3. We proceed by induction on the

pair of derivations used to derive r -→ s and r -→ t, with a case analysis on

the final rules in both derivations.

Case i:

Suppose r -→ s by E-IfTrue and r -→ t by E-Funny2. Then, from the forms

of these rules, we know that s = r2 and that t = if true then r′2 else r3,

where r2 -→ r′2. But then choosing u = r′2 gives us what we need, since we

know that s -→ r′2 and we can see that t -→ r′2 by E-IfTrue.

Case ii:

Suppose the final rule in the derivations of both r -→ s and r -→ t is E-If. By

the form of E-If, we know s must have the form if r′1 then r2 else r3 and

t must have the form if r′′1 then r2 else r3, where r1 -→ r′1 and r1 -→ r′′1 .

But then, by the induction hypothesis, there is some term r′′′1 with r′1 -→ r′′′1

and r′′1 -→ r′′′1 . We can complete the argument for this case by taking u =

if r′′′1 then r2 else r3 and observing that s -→ u and t -→ u by E-If.

The arguments for the other cases are similar. �

The proof of uniqueness of results now follows by a straightforward “dia-

gram chase.” Suppose that r -→∗ s and r -→∗ t.

Types and programming languages 6 / 24

Page 7: Types and programming languages - basics.sjtu.edu.cn

3.5.13

40 3 Untyped Arithmetic Expressions

3.5.13 Exercise [Recommended, ««]:

1. Suppose we add a new rule

if true then t2 else t3 -→ t3 (E-Funny1)

to the ones in Figure 3-1. Which of the above theorems (3.5.4, 3.5.7, 3.5.8,

3.5.11, and 3.5.12) remain valid?

2. Suppose instead that we add this rule:

t2 -→ t′2

if t1 then t2 else t3 -→ if t1 then t′2 else t3

(E-Funny2)

Now which of the above theorems remain valid? Do any of the proofs need

to change? �

Our next job is to extend the definition of evaluation to arithmetic expres-

sions. Figure 3-2 summarizes the new parts of the definition. (The notation in

the upper-right corner of 3-2 reminds us to regard this figure as an extension

of 3-1, not a free-standing language in its own right.)

Again, the definition of terms is just a repetition of the syntax we saw in

§3.1. The definition of values is a little more interesting, since it requires

introducing a new syntactic category of numeric values. The intuition is that

the final result of evaluating an arithmetic expression can be a number, where

a number is either 0 or the successor of a number (but not the successor of an

arbitrary value: we will want to say that succ(true) is an error, not a value).

The evaluation rules in the right-hand column of Figure 3-2 follow the

same pattern as we saw in Figure 3-1. There are four computation rules

(E-PredZero, E-PredSucc, E-IszeroZero, and E-IszeroSucc) showing how

the operators pred and iszero behave when applied to numbers, and three

congruence rules (E-Succ, E-Pred, and E-Iszero) that direct evaluation into

the “first” subterm of a compound term.

Strictly speaking, we should now repeat Definition 3.5.3 (“the one-step eval-

uation relation on arithmetic expressions is the smallest relation satisfying

all instances of the rules in Figures 3-1 and 3-2. . .”). To avoid wasting space

on this kind of boilerplate, it is common practice to take the inference rules

as constituting the definition of the relation all by themselves, leaving “the

smallest relation containing all instances. . .” as understood.

The syntactic category of numeric values (nv) plays an important role in

these rules. In E-PredSucc, for example, the fact that the left-hand side is

pred (succ nv1) (rather than pred (succ t1), for example) means that this

rule cannot be used to evaluate pred (succ (pred 0)) to pred 0, since this

I 3.5.4 If t → t ′ and t → t ′′, then t ′ = t ′′

I 3.5.7 Every value is in normal form.I 3.5.8 If t is in normal form, then t is a value.I 3.5.11 If t →∗ u and t →∗ u′, where u and u′ are both normal

forms, then u = u′.I 3.5.12 For every term t there is some normal form t ′ such

that t →∗ t ′.

Types and programming languages 7 / 24

Page 8: Types and programming languages - basics.sjtu.edu.cn

3.5.13

40 3 Untyped Arithmetic Expressions

3.5.13 Exercise [Recommended, ««]:

1. Suppose we add a new rule

if true then t2 else t3 -→ t3 (E-Funny1)

to the ones in Figure 3-1. Which of the above theorems (3.5.4, 3.5.7, 3.5.8,

3.5.11, and 3.5.12) remain valid?

2. Suppose instead that we add this rule:

t2 -→ t′2

if t1 then t2 else t3 -→ if t1 then t′2 else t3

(E-Funny2)

Now which of the above theorems remain valid? Do any of the proofs need

to change? �

Our next job is to extend the definition of evaluation to arithmetic expres-

sions. Figure 3-2 summarizes the new parts of the definition. (The notation in

the upper-right corner of 3-2 reminds us to regard this figure as an extension

of 3-1, not a free-standing language in its own right.)

Again, the definition of terms is just a repetition of the syntax we saw in

§3.1. The definition of values is a little more interesting, since it requires

introducing a new syntactic category of numeric values. The intuition is that

the final result of evaluating an arithmetic expression can be a number, where

a number is either 0 or the successor of a number (but not the successor of an

arbitrary value: we will want to say that succ(true) is an error, not a value).

The evaluation rules in the right-hand column of Figure 3-2 follow the

same pattern as we saw in Figure 3-1. There are four computation rules

(E-PredZero, E-PredSucc, E-IszeroZero, and E-IszeroSucc) showing how

the operators pred and iszero behave when applied to numbers, and three

congruence rules (E-Succ, E-Pred, and E-Iszero) that direct evaluation into

the “first” subterm of a compound term.

Strictly speaking, we should now repeat Definition 3.5.3 (“the one-step eval-

uation relation on arithmetic expressions is the smallest relation satisfying

all instances of the rules in Figures 3-1 and 3-2. . .”). To avoid wasting space

on this kind of boilerplate, it is common practice to take the inference rules

as constituting the definition of the relation all by themselves, leaving “the

smallest relation containing all instances. . .” as understood.

The syntactic category of numeric values (nv) plays an important role in

these rules. In E-PredSucc, for example, the fact that the left-hand side is

pred (succ nv1) (rather than pred (succ t1), for example) means that this

rule cannot be used to evaluate pred (succ (pred 0)) to pred 0, since this

I 3.5.4 If t → t ′ and t → t ′′, then t ′ = t ′′

I 3.5.7 Every value is in normal form.I 3.5.8 If t is in normal form, then t is a value.I 3.5.11 If t →∗ u and t →∗ u′, where u and u′ are both normal

forms, then u = u′.I 3.5.12 For every term t there is some normal form t ′ such

that t →∗ t ′.Types and programming languages 7 / 24

Page 9: Types and programming languages - basics.sjtu.edu.cn

3.5.13

Solution

1. 3.5.4 and 3.5.11 fail.

2. 3.5.4 fail.

3.5.11 If t →∗ u and t →∗ u′, where u and u′ are both normalforms, then u = u′.[Diamond Property] If r → s and r → t, with s 6= t, then there issome term u such that s →∗ u and t →∗ u.

Types and programming languages 8 / 24

Page 10: Types and programming languages - basics.sjtu.edu.cn

3.5.18

Suppose we want to change the evaluation strategy of ourlanguage so that the then and else branches of an if expression areevaluated (in that order) before the guard is evaluated. Show howthe evaluation rules need to change to achieve this effect.

Types and programming languages 9 / 24

Page 11: Types and programming languages - basics.sjtu.edu.cn

3.5.13

SolutionChange evaluation order, ”then”→ ”else”→ ”if”

t2 → t ′2if t1 then t2 else t3 → if t1 then t ′2 else t3

(E-Then)

t3 → t ′3if t1 then v2 else t3 → if t1 then v2 else t ′3

(E-Else)

t1 → t ′1if t1 then v2 else v3 → if t ′1 then v2 else v3

(E-If’)

if true then v2 else v3 → v2 (E-IfTrue’)

if false then v2 else v3 → v3 (E-IfFalse’)

”v” and ”t” have already been defined in the textbook!

Types and programming languages 10 / 24

Page 12: Types and programming languages - basics.sjtu.edu.cn

Homework 2

Types and programming languages 11 / 24

Page 13: Types and programming languages - basics.sjtu.edu.cn

hw2.1

In Problem 1 - 3, a ”date” is an OCaml value of type int*int*int,where the first part is the year, the second part the month, and thethird part the day.Write a function is older that takes two dates and evaluates to trueor false. It evaluates to true if the first argument is a date thatcomes before the second argument. (If the two dates are the same,the result is false.)

Types and programming languages 12 / 24

Page 14: Types and programming languages - basics.sjtu.edu.cn

hw2.1

Write a function is older that takes two dates and evaluates to trueor false. It evaluates to true if the first argument is a date thatcomes before the second argument. (If the two dates are the same,the result is false.)

Solution

l e t i s o l d e r ( y1 , m1, d1 ) ( y2 , m2, d2 ) =i f y1 != y2 then y1 < y2e l s e i f m1 != m2 then m1 < m2e l s e d1 < d2 ; ;

Types and programming languages 13 / 24

Page 15: Types and programming languages - basics.sjtu.edu.cn

hw2.2

Write a function what month that takes a day of year (i.e., an intbetween 1 and 365) and returns what month that day is in (1 forJanuary, 2 for February, etc.). Use a list holding 12 integers and donot need to consider leap years.

Types and programming languages 14 / 24

Page 16: Types and programming languages - basics.sjtu.edu.cn

hw2.2

Solution

e x c e p t i o n OUT OF RANGE ; ;l e t m o n t h d a y s l i s t = [ 3 1 ; 2 8 ; 3 1 ; 3 0 ; 3 1 ; 3 0 ; 3 1 ; 3 1 ;

3 0 ; 3 1 ; 3 0 ; 3 1 ] ; ;l e t what month day =

i f day <= 0 | | day > 365 thenr a i s e OUT OF RANGE

e l s el e t r e c h e l p e r day l i s t =

match l i s t w i t hhead : : t a i l -> i f day > head

then 1+ h e l p e r ( day-head ) t a i le l s e 1

i nh e l p e r day m o n t h d a y s l i s t ; ;

Types and programming languages 15 / 24

Page 17: Types and programming languages - basics.sjtu.edu.cn

hw2.3

Write a function reasonable date that takes a date and determinesif it describes a real date in the common era. A date” has apositive year (year 0 did not exist), a month between 1 and 12, anda day appropriate for the month. Solutions should properly handleleap years. Leap years are years that are either divisible by 400 ordivisible by 4 but not divisible by 100. (Do not worry about dayspossibly lost in the conversion to the Gregorian calendar in theLate 1500s.)

Types and programming languages 16 / 24

Page 18: Types and programming languages - basics.sjtu.edu.cn

hw2.3

Solution

l e t m o n t h d a y s l i s t = [ 3 1 ; 2 8 ; 3 1 ; 3 0 ; 3 1 ; 3 0 ; 3 1 ; 3 1 ;3 0 ; 3 1 ; 3 0 ; 3 1 ] ; ;

l e t r e a s o n a b l e d a t e ( y , m, d ) =l e t r e c g e t d a y s month days=

match days w i t hd : : days ’ ->

i f month = 1 then de l s e g e t d a y s ( month-1) days ’

and i s l e a p y e a r y e a r =( y e a r mod 400 = 0) | |( y e a r mod 4 = 0 && y e a r mod 100 != 0)

i ni f y<1 | | m<1 | | m>12 | | d<1 then f a l s ee l s e i f m=2 && ( i s l e a p y e a r y )

then d <= 29e l s e d <= ( g e t d a y s m m o n t h d a y s l i s t ) ; ;

Types and programming languages 17 / 24

Page 19: Types and programming languages - basics.sjtu.edu.cn

hw2.4

Write a function only capitals that takes a string list and returns astring list that has only the strings in the argument that start withan uppercase letter. For example, given [”Aa”;”Bb”;”cc”], itshould return [”Aa”;”Bb”]; Given [”1a”;”bb”;”cc”], it shouldreturn []. Assume all strings have at least 1 character. UseList.filter filter function list, and String.get string n-index to makea 1-2 line solution.

Types and programming languages 18 / 24

Page 20: Types and programming languages - basics.sjtu.edu.cn

hw2.4

Solution

l e t o n l y c a p i t a l s s t r i n g l i s t =L i s t . f i l t e r( fun s -> ( S t r i n g . g e t s 0) >= ’A’

&& ( S t r i n g . g e t s 0) <= ’Z ’ )s t r i n g l i s t

Types and programming languages 19 / 24

Page 21: Types and programming languages - basics.sjtu.edu.cn

hw2.4

A simpler solution

l e t o n l y c a p i t a l s =L i s t . f i l t e r( fun s -> l e t c = S t r i n g . g e t s 0

i n c >= ’A’ && c <= ’Z ’ )

Types and programming languages 20 / 24

Page 22: Types and programming languages - basics.sjtu.edu.cn

hw2.5

Write a function longest string1 that takes a string list and returnsthe longest string in the list. If the list is empty, return ””. In thecase of a tie, return the string closest to the beginning of the list.Use List.fold left, String.length, and no recursion (other than theimplementation of List.fold left is recursive).

Types and programming languages 21 / 24

Page 23: Types and programming languages - basics.sjtu.edu.cn

hw2.5

Solution

l e t l o n g e s t s t r i n g 1 s t r i n g l i s t =l e t l o n g e s t s t r 1 s t r 2 =

i f S t r i n g . l e n g t h s t r 1 >= S t r i n g . l e n g t h s t r 2then s t r 1 e l s e s t r 2

i nL i s t . f o l d l e f t l o n g e s t ”” s t r i n g l i s t

Types and programming languages 22 / 24

Page 24: Types and programming languages - basics.sjtu.edu.cn

hw2.6

Write a function longest string2 that is exactly like longest string1except in the case of ties it returns the string closest to the end ofthe list. Your solution should be almost an exact copy oflongest string1. Still use List.fold left and String.length.

Types and programming languages 23 / 24

Page 25: Types and programming languages - basics.sjtu.edu.cn

hw2.6

Solution

l e t l o n g e s t s t r i n g 2 s t r i n g l i s t =l e t l o n g e s t s t r 1 s t r 2 =

i f S t r i n g . l e n g t h s t r 1 > S t r i n g . l e n g t h s t r 2then s t r 1 e l s e s t r 2

i nL i s t . f o l d l e f t l o n g e s t ”” s t r i n g l i s t

Types and programming languages 24 / 24