Docsity

Problems on Numeric Code Modularization using Streams and Lazy Execution - Prof. Gary Leav, Assignments of Programming Languages

Toggle sidebar
bg1
COP 4020 — Programming Languages 1 March 31, 2008
Homework 4: Declarative Concurrency
Due: problems 3–4, 8 Monday, March 24, 2007 at 11pm; problems 5, 7 Wednesday, March 26, 2007 at
11pm; problems 9–17, 19-20, Wednesday, April 2, 2007 at 11pm.
In this homework you will learn about the declarative concurrent model and basic techniques of declara-
tive concurrent programming. The programming techniques include stream programming and lazy functional
programming [Concepts] [UseModels]. A few problems also make comparisons with the declarative model
and with concurrency features in Java [MapToLanguages]. A few problems also make comparisons between
programming techniques [EvaluateModels]; you may want to look at Problem 20 on page 11 right now so
you can be thinking about it while you do the other problems.
Your code should be written in the declarative concurrent model, so you must not use cells and assignment
in your Oz solutions. (Furthermore, note that the declarative model does not include the primitive IsDet
or the library function IsFree; thus you are also prohibited from using either of these functions in your
solutions.) But please use all linguistic abstractions and syntactic sugars that are helpful.
Feel free to use helping functions as well. Unless we specifically say how you are to solve a problem, feel
free to use any functions from the Oz library (base environment), especially functions like Map and FoldR.
For all programing tasks, you must run your code using the Mozart/Oz system. Oz code with tests for
various problems is available in a zip file, which you can download from the course resources web page.
For testing, you may want to use tests based on our code in the course library file TestingNoStop.oz.
Turn in (on WebCT) your code and output of your testing for all exercises that require code. Please upload
code as text files with the name given in the problem or testing file and with the suffix .oz. Please use the
name of the main function as the name of the file. Please upload test output and English answers as plain text
files with suffix .txt or as PDF files with suffix .pdf. If you have a mix of code and English, use a text file
with a .oz file suffix, and put comments in the file for the English parts. (In any case, don’t put any spaces
in your file names!)
If we provide tests and your code passes all of them, you can just indicate with a comment in the code
that your code passes all the tests. Otherwise it is necessary for you to provide us test code and/or test output.
If the code does not pass some tests, indicate in your code with a comment what tests did not pass, and try
to say why, as this enhances communication and makes commenting on the code easier and more specific to
your problem than just leaving the buggy code without comments.
If you’re not sure how to use our testing code, ask us for help.
Your code should compile with Oz, if it doesn’t you probably should keep working on it. If you don’t
have time, at least tell us that you didn’t get it to compile.
Be sure to clearly label what problem each area of code solves with a comment.
You might loose points even if your code is passing all the tests, if you don’t follow the grammar or if
your code is confusing or needlessly inefficient. Make sure you don’t have extra case clauses or unnecessary
if tests, make sure you are using as much function definitions/calls as needed, check if you are making
unnecessary loops or passes in your code, efficient code means full mark, working code does not necessarily
mean full mark.
If you are using Windows Vista, you can use Browse if you reinstall, see our Running Oz web page.1
Don’t hesitate to contact the staff if you are stuck at some point.
Read Chapter 4 of the textbook [RH04]. (See the syllabus for optional readings.)
1If you are using Vista and Browse doesn’t work for you, but you don’t want to reinstall Oz, then instead of using Browse use
Show (or to see strings, System.showInfo). However, this is somewhat problematic because Show (and showInfo) only show
you the instantaneous view of their argument. In essence there will be a race condition between other threads and the thread using Show.
One way around this is to use the Wait operation in Oz (see Section 10.1 of “The Oz Base Environment” [DKS06]). For example, write
{Wait X} {Show X} where the textbook has {Browse X}. In cases where you don’t have a single variable to wait on, you can
introduce delays using the Delay procedure (see Section 10.3 of “The Oz Base Environment” [DKS06]). For example, use {Delay
5000} {Show Lst} where code in the textbook shows {Browse Lst}. You may have to adjust the timing argument to delay
(which is measured in milliseconds) to fit the problem.
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Problems on Numeric Code Modularization using Streams and Lazy Execution - Prof. Gary Leav and more Assignments Programming Languages in PDF only on Docsity!

COP 4020 — Programming Languages 1 March 31, 2008

Homework 4: Declarative Concurrency

Due: problems 3–4, 8 Monday, March 24, 2007 at 11pm; problems 5, 7 Wednesday, March 26, 2007 at

11pm; problems 9–17, 19-20, Wednesday, April 2, 2007 at 11pm.

In this homework you will learn about the declarative concurrent model and basic techniques of declara-

tive concurrent programming. The programming techniques include stream programming and lazy functional

programming [Concepts] [UseModels]. A few problems also make comparisons with the declarative model

and with concurrency features in Java [MapToLanguages]. A few problems also make comparisons between

programming techniques [EvaluateModels]; you may want to look at Problem 20 on page 11 right now so

you can be thinking about it while you do the other problems.

Your code should be written in the declarative concurrent model, so you must not use cells and assignment

in your Oz solutions. (Furthermore, note that the declarative model does not include the primitive IsDet

or the library function IsFree; thus you are also prohibited from using either of these functions in your

solutions.) But please use all linguistic abstractions and syntactic sugars that are helpful.

Feel free to use helping functions as well. Unless we specifically say how you are to solve a problem, feel

free to use any functions from the Oz library (base environment), especially functions like Map and FoldR.

For all programing tasks, you must run your code using the Mozart/Oz system. Oz code with tests for

various problems is available in a zip file, which you can download from the course resources web page.

For testing, you may want to use tests based on our code in the course library file TestingNoStop.oz.

Turn in (on WebCT) your code and output of your testing for all exercises that require code. Please upload

code as text files with the name given in the problem or testing file and with the suffix .oz. Please use the

name of the main function as the name of the file. Please upload test output and English answers as plain text

files with suffix .txt or as PDF files with suffix .pdf. If you have a mix of code and English, use a text file

with a .oz file suffix, and put comments in the file for the English parts. (In any case, don’t put any spaces

in your file names!)

If we provide tests and your code passes all of them, you can just indicate with a comment in the code

that your code passes all the tests. Otherwise it is necessary for you to provide us test code and/or test output.

If the code does not pass some tests, indicate in your code with a comment what tests did not pass, and try

to say why, as this enhances communication and makes commenting on the code easier and more specific to

your problem than just leaving the buggy code without comments.

If you’re not sure how to use our testing code, ask us for help.

Your code should compile with Oz, if it doesn’t you probably should keep working on it. If you don’t

have time, at least tell us that you didn’t get it to compile.

Be sure to clearly label what problem each area of code solves with a comment.

You might loose points even if your code is passing all the tests, if you don’t follow the grammar or if

your code is confusing or needlessly inefficient. Make sure you don’t have extra case clauses or unnecessary

if tests, make sure you are using as much function definitions/calls as needed, check if you are making

unnecessary loops or passes in your code, efficient code means full mark, working code does not necessarily

mean full mark.

If you are using Windows Vista, you can use Browse if you reinstall, see our Running Oz web page.^1

Don’t hesitate to contact the staff if you are stuck at some point.

Read Chapter 4 of the textbook [RH04]. (See the syllabus for optional readings.)

(^1) If you are using Vista and Browse doesn’t work for you, but you don’t want to reinstall Oz, then instead of using Browse use

Show (or to see strings, System.showInfo). However, this is somewhat problematic because Show (and showInfo) only show you the instantaneous view of their argument. In essence there will be a race condition between other threads and the thread using Show. One way around this is to use the Wait operation in Oz (see Section 10.1 of “The Oz Base Environment” [DKS06]). For example, write {Wait X} {Show X} where the textbook has {Browse X}. In cases where you don’t have a single variable to wait on, you can introduce delays using the Delay procedure (see Section 10.3 of “The Oz Base Environment” [DKS06]). For example, use {Delay 5000} {Show Lst} where code in the textbook shows {Browse Lst}. You may have to adjust the timing argument to delay (which is measured in milliseconds) to fit the problem.

Thread and Dataflow Behavior Semantics

The following problems explore the semantics of the declarative concurrent model.

1. (suggested practice)

Do problem 1 in section 4.11 of the textbook [RH04] (Thread Semantics). Note that part (b) should

read (according to the errata) “All of these executions.. .”. For part (b) the particular change you make

is up to you, but test your program code to make sure it works.

2. (10 points; extra credit) [Concepts]

Do problem 2 in section 4.11 of the textbook [RH04] (Threads and garbage collection).

3. (10 points) [Concepts]

Do problem 4 in section 4.11 of the textbook [RH04] (Order-determining concurrency).

4. This problem explores threads and dataflow in Java [MapToLanguages]

For more information about threads in Java see, for example, The Java Tutorial [CW98], which is

online at http://java.sun.com/docs/books/tutorial/. The concurrency section of that

tutorial has several examples.

(a) (10 points) Write, in Java, write a version of the program in the textbook’s problem 4 (of section

4.11) in which the Oz program’s dataflow variables A, B, C, and D are represented by fields

(perhaps static fields) in the Java code. Call your Java class FourThreads. This version the

Java code does not need to faithfully match the semantics of Oz exactly, just translate to Java in

the most straightforward way possible.

Hints: You will need to either use package-visible fields or nest your subclasses of Thread or

subtypes of Runnable within your main FourThreads class. You can use anonymous inner

classes to make your code shorter.

(b) (5 points) How much extra code is present in the Java version compared with the Oz code?

(c) (5 points) Does your Java code have the possibility of race conditions? Briefly explain.

(d) (5 points) Does your Java code always give the same answer as the Oz Code? Briefly explain.

(e) (40 points) Write, in Java, a class IntDataflowVariable, with operations int get()

and void set(int). The get operation should suspend the calling thread until the set

method is called. The set method should throw an IllegalArgumentException if it

is called again with a different argument than the value used the first time it was called. Test

by using it to write another version of the textbook’s problem 4 (of section 4.11) using in-

stances of your class IntDataflowVariable in place of the integer fields. Call this class

FourThreadsWithDataflow. Running this class’s main method should always give the

same output as the Oz code.

5. (10 points) [Concepts] [UseModels]

Do problem 5 in section 4.11 of the textbook [RH04] (The Wait Operation).

6. (20 points; extra credit) [Concepts]

Do problem 7 in section 4.11 of the textbook [RH04] (Programmed triggers using higher-order pro-

gramming). Note that the example mentioned in the problem is the example with DGenerate and

DSum that is the first example shown in section 4.3.3.1.

7. (20 points) [Concepts]

Do problem 8 in section 4.11 of the textbook [RH04] (Dataflow behavior in a concurrent setting).

% $Id: FloatPredicates.oz,v 1.3 2007/10/23 02:14:21 leavens Exp leavens $ %% Some functions to do approximate equality of floating point numbers. %% AUTHOR: Gary T. Leavens

declare %% Return true iff the difference between X and Y %% is no larger than Epsilon fun {Within Epsilon X Y} {Abs X-Y} =< Epsilon end

%% Partly curried version of Within fun {WithinMaker Epsilon} fun {$ X Y} {Within Epsilon X Y} end end

%% Return true iff the corresponding lists are %% equal relative to the given predicate fun {CompareLists Pred Xs Ys} case Xs#Ys of nil#nil then true [] (X|Xr)#(Y|Yr) then {Pred X Y} andthen {CompareLists Pred Xr Yr} else false end end

%% Return true iff the lists are equal %% in the sense that the corresponging elements %% are equal to within Epsilon fun {WithinLists Epsilon Xs Ys} {CompareLists {WithinMaker Epsilon} Xs Ys} end

%% Return true iff the ratio of X-Y to Y is within Epsilon fun {Relative Epsilon X Y} {Abs X-Y} =< Epsilon*{Abs Y} end

%% Partly curried version of Relative fun {RelativeMaker Epsilon} fun {$ X Y} {Relative Epsilon X Y} end end

%% Return true iff the lists are equal %% in the sense that the corresponging elements %% are relatively equal to within Epsilon fun {RelativeLists Epsilon Xs Ys} {CompareLists {RelativeMaker Epsilon} Xs Ys} end

%% A useful tolerance for testing StandardTolerance = 1.0e~

%% A convenience for testing, relative equality with a fixed Epsilon ApproxEqual = {RelativeMaker StandardTolerance}

Figure 1: Comparisons for floating point numbers. This code is available in the course lib directory.

% $Id: FloatTesting.oz,v 1.5 2008/03/24 15:43:04 leavens Exp leavens $ % Testing for floating point numbers. % AUTHOR: Gary T. Leavens

\insert ’FloatPredicates.oz’ \insert ’TestingNoStop.oz’

declare %% TestMaker returns a procedure P such that {P Actual ’=’ Expected} %% is true if {FloatCompare Epsilon Actual Expected} (for Floats) %% or if {FloatListCompare Epsilon Actual Expected} (for lists of Floats) %% If so, print a message, otherwise throw an exception. fun {TestMaker FloatCompare FloatListCompare Epsilon} fun {Compare Actual Expected} if {IsFloat Actual} andthen {IsFloat Expected} then {FloatCompare Epsilon Actual Expected} elseif {IsList Actual} andthen {IsList Expected} then {FloatListCompare Epsilon Actual Expected} else false end end in proc {$ Actual Connective Expected} if {Compare Actual Expected} then {System.showInfo {Value.toVirtualString Actual 5 20}

’ ’ # Connective # ’ ’

{Value.toVirtualString Expected 5 20}}

else {System.showInfo ’TEST FAILURE: ’

{Value.toVirtualString Actual 5 20}

’ ’ # Connective # ’ ’

{Value.toVirtualString Expected 5 20}

} end end end

WithinTest = {TestMaker Within WithinLists StandardTolerance} RelativeTest = {TestMaker Relative RelativeLists StandardTolerance}

Figure 2: Testing code for floating point. This puts output on standard output (the Oz Emulator win-

dow). The file FloatPredicates is shown in Figure 1 on the preceding page. This file is available in the

course lib directory. To use it, copy the files from the course directory to your own directory and then put

\insert ’FloatTesting.oz’ in your file.

(b) (5 points) [Concepts] [UseModels]

Does your function Approximations have to be declared to be lazy? Briefly explain.

10. (10 points) [UseModels]

Write a function

ConvergesTo: < fun {$ < fun {$ T T}: Bool>}: T>

such that {ConvergesTo Xs Pred} looks down the stream Xs to find the first two consecutive

elements of Xs that satisfy Pred, and it returns the second of these consecutive elements. (It will

never return if there is no such pair of consecutive elements.) Figure 5 on the following page gives

some examples.

11. (10 points) [UseModels]

Using WithinMaker from Figure 1 on page 4 and other functions given above, in particular ConvergesTo,

write a function

SquareRoot: < fun {$ Float Float Float}: Float>

such that {SquareRoot A0 Epsilon N} returns an approximation to the square root of N that

is within Epsilon. The parameter A0 is used as an initial guess in the Newton-Raphson method.

Examples are given in Figure 6 on the next page.

12. (10 points) [UseModels]

Using RelativeMaker from Figure 1 on page 4 and the other pieces given above, in particular

ConvergesTo, write a function

RelativeSquareRoot: < fun {$ Float Float Float}: Float>

such that {RelativeSquareRoot A0 Epsilon N} returns an approximation to the square root

of N that only has a relative error of Epsilon. The parameter A0 is used as an initial guess in the

Newton-Raphson method. When iterating, keep going until the ratio of the difference between the

last and the previous approximation to the last approximation approaches 0, instead of waiting for the

differences between the approximations themselves to approach zero. (This is equivalent to iterating

until the ratio of the last two approximations approaches 1.) This is test for convergence is better for

square roots of very large numbers, and for square roots of very small numbers. Examples are given in

Figure 7 on page 9.

13. (15 points) [UseModels]

You may recall that the derivative of a function F at a point X can be approximated by the following

function.

% $Id: EasyDiff.oz,v 1.3 2007/10/31 00:44:27 leavens Exp leavens $ declare fun {EasyDiff F X Delta} ({F (X+Delta)} - {F X}) / Delta end

Good approximations are given by small values of Delta, but if Delta is too small, then rounding

errors may swamp the result. One way to choose Delta is to compute a sequence of approximations,

starting with a reasonably large one. (In this way, if {WithinMaker Epsilon} is used to select

the first approximation that is accurate enough, this can reduce the risk of a rounding error affecting

the result, as we will show in the next problem.)

In this problem your task is to write a function

DiffApproxims: < fun {$ Float < fun {$ Float}: Float> Float}:

>

% $Id: ConvergesToTest.oz,v 1.5 2007/10/31 00:45:52 leavens Exp leavens $ \insert ’ConvergesTo.oz’ \insert ’FloatTesting.oz’

fun lazy {Repeat X} X|{Repeat X} end

{StartTesting ’ConvergesTo...’} {WithinTest {ConvergesTo {Append [1.0 3.5 4.5] {Repeat 7.0}} {WithinMaker 1.01} } ’~=~’ 4.5} {WithinTest {ConvergesTo {Append [1.0 32.5 17.2346 10.474 8.29219 8.00515] {Repeat 8.0}} {WithinMaker 0.5} } ’~=~’ 8.00515}

Figure 5: Tests for Problem 10 on the previous page.

% $Id: SquareRootTest.oz,v 1.2 2007/10/31 00:35:49 leavens Exp leavens $ \insert ’SquareRoot.oz’ \insert ’FloatTesting.oz’ {StartTesting ’SquareRoot...’} Millionth = 0. WithinMillionth = {TestMaker Within WithinLists Millionth} {WithinMillionth {SquareRoot 1.0 Millionth 2.0} ’~=~’ 1.41421356} {WithinMillionth {SquareRoot 1.0 Millionth 4.0} ’~=~’ 2.0} {WithinMillionth {SquareRoot 1.0 Millionth 64.0} ’~=~’ 8.0} {WithinMillionth {SquareRoot 1.0 Millionth 3.14159} ’~=~’ 1.7724531}

Figure 6: Tests for Problem 11 on the preceding page.

% $Id: DifferentiateTest.oz,v 1.2 2007/10/31 00:37:26 leavens Exp leavens $ \insert ’Differentiate.oz’ \insert ’FloatTesting.oz’ {StartTesting ’Differentiate...’} Millionth = 0. WithinMillionth = {TestMaker Within WithinLists Millionth} {WithinMillionth {Differentiate Millionth 500.0 fun {$ X} XX end 20.0} ’~=~’ 40.0} {WithinMillionth {Differentiate Millionth 100.0 fun {$ X} XX*X end 10.0} ’~=~’ 300.0}

Figure 9: Tests for Problem 14.

such that {DiffApproxims Delta0 F X} returns an infinite list of approximations to the deriva-

tive of F at X, where at each step, the current Delta is halved. Examples are given in Figure 8 on

page 9.

Hint: do you need to make something lazy to make this work?

14. (15 points) [UseModels]

Using the pieces given above, in particular ConvergesTo and DiffApproxims, write a function

Differentiate: < fun {$ Float Float < fun {$ Float}: Float> Float}:

Float>

such that {Differentiate Epsilon Delta0 F N} returns an approximation that is accurate

to within Epsilon to the derivative of F at N. Use the previous problem (Problem 13 on page 7) with

Delta0 as the initial value for Delta. Examples are given in Figure 9.

Laziness Problems

The following problems explore more about laziness and its utility.

15. (10 points) [EvaluateModels]

Do problem 12 in section 4.11 of the textbook [RH04] (Laziness and incrementality).

16. (10 points) [EvaluateModels]

Do problem 13 in section 4.11 of the textbook [RH04] (Laziness and monolithic functions).

17. (20 points) [Concepts] [UseModels]

Do problem 16 in section 4.11 of the textbook [RH04] (By-need execution).

To explain this problem and provide a test, call your procedure that solves this problem RequestCalc.

Note that it should be a procedure, not a function. Then when run as in Figure 10 on the next page

it should show in the Browser window first Z, then it should show requestin, then the Z should

change to O|, then you should see request2in, and then the first line should change to 0|1|.

Hints: think about what actions in Oz request (demand) calculation of a variable identifier’s value. And

think about what new features we have in this chapter that can be used to prevent a thread from waiting

for something.

18. (15 points; extra credit) [Concepts]

Do problem 18 in section 4.11 of the textbook [RH04] (Concurrency and Exceptions). (Hint: the

“abstract machine semantics” is the operational semantics of Oz, which is described in the textbook’s

% $Id: RequestCalcTest.oz,v 1.2 2008/03/23 16:38:27 leavens Exp leavens $ \insert ’TestingNoStop.oz’ \insert ’RequestCalc.oz’

% Testing declare Z fun lazy {SGen Y} {Delay 5000} Y|{SGen Y+1} end Z = {SGen 0} {Browse Z}

{Delay 2000} {RequestCalc Z} {Browse requestin} {Delay 2000} {RequestCalc Z.2} {Browse request2in}

Figure 10: Tests for Problem 17 on the preceding page.

sections 2.4, 2.7.2, 4.1, and 4.9.1. You don’t have to do anything formal or especially mathematical

with the operational semantics.)

19. (15 points) [Concepts] [EvaluateModels]

Do problem 19 in section 4.11 of the textbook [RH04] (Limitations of Declarative Concurrency).

(Note: there is a typo in the book, the Merge function has only two input streams, not three.)

20. (20 points) [EvaluateModels]

Make a table listing all the different programming techniques, the characteristics of problems that

are best solved with these techniques (i.e., when to use the techniques), and the name of at least one

example of that technique.

programming problem

technique characteristics example(s)

recursion (over grammars)

higher-order functions

stream programming

lazy functions

21. (20 points; extra credit) [IsDet and State]

The instructions for this homework state that you are not to use Oz’s built-in function IsDet in writing

your code, since that is not part of the declarative model. Show why the use of IsDet takes you

outside the declarative model by using it to simulate a Boolean-valued cell. (Of course, you are to

do this only using the declarative model and IsDet.) Let’s call the ADT that you are programming

CellWithIsDet. Then your code should have the following interface.

NewCellWithIsDet: < fun {$ Bool}: CellWithIsDet>

CWIDAccess: < fun {$ CellWithIsDet}: Bool>

CWIDAssign: < proc {$ CellWithIsDet Bool}>

Testing should show that you can change the value of a CellWithIsDet object from true to false

and back again, as shown in Figure 11 on the next page.

References

[CW98] Mary Campione and Kathy Walrath. The Java Tutorial Second Edition: Object-Oriented Program-

ming for the Internet. The Java Series. Addison-Wesley, Reading, MA, second edition, 1998.

[DKS06] Denys Duchier, Leif Kornstaedt, and Christian Schulte. The Oz Base Environment. mozart-oz.org,

June 2006. Version 1.3.2.

[RH04] Peter Van Roy and Seif Haridi. Concepts, Techniques, and Models of Computer Programming.

The MIT Press, Cambridge, Mass., 2004.