Review Questions
2. What does a lambda expression specify?
The predicate function is often given as a lambda expression, which in
ML is defined exactly like a function, except with the fn reserved word,
instead of fun, and of course the lambda expression is nameless.
5. Explain why QUOTE is needed for a parameter that is a data list.
To avoid evaluating a parameter, it is first given as a parameter to the
primitive function QUOTE, which simply returns it without change.
6. What is a simple list?
A list which membership of a given atom in a given list that does not include sublists.
7. What does the abbreviation REPL stand for?
REPL stand for read-evaluate-print loop.
11. What are the two forms of DEFINE?
The simplest form of DEFINE is one used to bind a name to the value of an expression. This form is
(DEFINE symbol expression)
The general form of such a DEFINE is
(DEFINE (function_name parameters)
(expression)
)
13. Why are CAR and CDR so named?
The names of the CAR and CDR functions are peculiar at best. The origin
of these names lies in the first implementation of LISP, which was on an
IBM 704 computer. The 704’s memory words had two fields, named
decrement and address, that were used in various operand addressing
strategies. Each of
these fields could store a machine memory address. The 704 also included
two machine instructions, also named CAR (contents of the address part
of a register) and CDR (contents of the decrement part of a register),
that extracted the associated fields. It was natural to use the two
fields to store the two pointers
of a list node so that a memory word could neatly store a node. Using
these conventions, the CAR and CDR instructions of the 704 provided
efficient list selectors. The names carried over into the primitives of
all dialects of LISP.
18. What is tail recursion? Why is it important to define
functions that use recursion to specify repetition to be tail recursive?
A function is tail recursive if its recursive call is the last operation
in the function. This means that the return value of the recursive call
is the return value of the nonrecursive call to the function. It is
important to specify repetition to be tail recursive because it is more
efficient(increase the efficiency).
19. Why were imperative features added to most dialects of LISP?
LISP began as a pure functional language but soon acquired some
important imperative features to increased its execution efficiency.
26. What is type inferencing, as used in ML?
Type inference refers to the automatic deduction of the type of an
expression in a programming language. If some, but not all, type
annotations are already present it is referred to as type
reconstruction.
29. What is a curried function?
Curried functions a function which a new functions can be constructed from them by partial evaluation.
30. What does partial evaluation mean?
Partial evaluation means that the function is evaluated with actual
parameters for one or more of the leftmost formal parameters.
32. What is the use of the evaluation environment table?
A table called the evaluation environment stores the names of all
implicitly and explicitly declared identifiers in a program, along with
their types. This is like a run-time symbol table.
33. Explain the process of currying.
The process of currying replaces a function with more than one parameter
with a function with one parameter that returns a function that takes
the other parameters of the initial function.
Problem Set
8. How is the functional operator pipeline ( |> ) used in F#?
The pipeline operator is a binary operator that sends the value of
its left operand, which is an expression, to the last parameter of the
function call, which is the right operand. It is used to chain together
function calls while flowing the data being processed to each call.
9. What does the following Scheme function do?
(define ( y s lis)
(cond
(( null? lis) ‘ () )
((equal? s (car lis)) lis)
(else (y s (cdr lis)))
))
y returns the given list with leading elements removed up to but not
including the first occurrence of the first given parameter.
10.What does the following Scheme function do?
(define ( x lis)
(cond
(( null? lis) 0 )
(( not(list? (car lis)))
(cond
((eq? (car lis) #f) (x (cdr lis)))
(else (+1 (x (cdr lis))))))
(else (+ (x (car lis)) (x (cdr lis))))
x returns the number of non-#f atoms in the given list
My First Blog!
Kamis, 27 Juni 2013
Concepts of Programming Languages Assignment - Chapter 14
Review Questions
1. Define exception, exception handler, raising an exception, disabling an exception, continuation, finalization, and built-in exception.
An exception is an unusual event that is detectable by either hardware or software and that may require special processing. The special processing that may be required when an exception is detected is called exception handling. The processing is done by a code unit or segment called an exception handler. An exception is raised when its associated event occurs. In some situations, it may be desirable to ignore certain hardware-detectable exceptions—for example, division by zero—for a time. This action would be done by disabling the exception. After an exception handler executes, either control can transfer to somewhere in the program outside of the handler code or
Program execution can simply terminate. We term this the question of control continuation after handler execution, or simply continuation. In some situations, it is necessary to complete some computation regardless of how subprogram execution terminates. The ability to specify such a computation is called finalization. Built-in exceptions have a built-in meaning, it is generally inadvisable to use these to signal program-specific error conditions. Instead we introduce a new exception using an exception declaration, and signal it using a raise expression when a run-time violation occurs. That way we can associate specific exceptions with specific pieces of code, easing the process of tracking down the source of the error.
7. Where are unhandled exceptions propagated in Ada if raised in a subprogram?
A block? A package body? A task?
When an exception is raised in a block, in either its declarations or executable statements, and the block has no handler for it, the exception is propagated to the next larger enclosing static scope, which is the code that “called” it. The point to which the exception is propagated is just after the end of the block in which it occurred, which is its “return” point. When an exception is raised in a package body and the package body has no handler for the exception, the exception is propagated to the declaration section of the unit containing the package declaration. If the package happens to be a library unit (which is separately compiled), the program is terminated.
If an exception occurs at the outermost level in a task body (not in a nested block) and the task contains a handler for the exception, that handler is executed and the task is marked as being completed. If the task does not have a handler for the exception, the task is simply marked as being completed; the exception is not propagated. The control mechanism of a task is too complex to lend itself to a reasonable and simple answer to the question of where its unhandled exceptions should be propagated.
10. What are the four exceptions defined in the Standard package of Ada?
The four exception defined in the standard package of Ada are Constraint_Error, Program_Error, Storage_Error, Tasking_Error
11. What is the use of suppress pragma in Ada?
An Ada pragma is a directive to the compiler. Certain run-time checks that are parts of the built-in exceptions can be disabled in Ada programs by use of the Suppress pragma, the simple form of which is pragma Suppress(check_name)
where check_name is the name of a particular exception check. The Suppress pragma can appear only in declaration sections. When it appears, the specified check may be suspended in the associated block or program unit of which the declaration section is a part. Explicit raises are not affected by Suppress. Although it is not required, most Ada compilers implement the Suppress pragma.
13. Describe three problems with Ada’s exception handling.
There are several problems with Ada’s exception handling. One problem is the propagation model, which allows exceptions to be propagated to an outer scope in which the exception is not visible. Also, it is not always possible to determine the origin of propagated exceptions. Another problem is the inadequacy of exception handling for tasks. For example, a task that raises an exception but does not handle it simply dies. Finally, when support for object-oriented programming was added in Ada 95, its exception handling was not extended to deal with the new constructs. For example, when several objects of a class are created and used in a block and one of them propagates an exception, it is impossible to determine which one raised the exception.
14. What is the name of all C++ exception handlers?
Each catch function is an exception handler. A catch function can have only a single formal parameter, which is similar to a formal parameter in a function definition in C++, including the possibility of it being an ellipsis (. . .). A handler with an ellipsis formal parameter is the catch-all handler; it is enacted for any raised exception if no appropriate handler was found. The formal parameter also can be a naked type specifier, such as float, as in a function prototype. In such a case, the only purpose of the formal parameter is to make the handler uniquely identifiable. When information about the exception is to be passed to the handler, the formal parameter includes a variable name that is used for that purpose. Because the class of the parameter can be any user-defined class, the parameter can include as many data members as are
necessary.
15. Which standard libraries define and throw the exception out_of_range in C++?
The exception out_of_range in C++ thrown by library container classes
16. Which standard libraries define and throw the exception overflow_error in C++?
the exception overflow_error in C++ thrown by math library functions
19. State the similarity between the exception handling mechanism in C++ and Ada
In some ways, the C++ exception-handling mechanism is similar to that of Ada. For example, unhandled exceptions in functions are propagated to the function’s caller.
20. State the differences between the exception handling mechanism in C++ and Ada
There are no predefined hardware-detectable exceptions that can be handled by the user, and exceptions are not named. Exceptions are connected to handlers through a parameter type in which the formal parameter may be omitted. The type of the formal parameter of a handler determines the condition under which it is called but may have nothing whatsoever to do with the nature of the raised exception.
24. What is the difference between checked and unchecked exceptions in Java?
Exceptions of class Error and RuntimeException and their descendants are called unchecked exceptions. All other exceptions are called checked exceptions. Unchecked exceptions are never a concern of the compiler. However, the compiler ensures that all checked exceptions a method can throw are either listed in its throws clause or handled in the method. Note that checking this at compile time differs from C++, in which it is done at run time. The reason why exceptions of the classes Error and RuntimeException and their descendants are unchecked is that any method could throw them. A program can catch unchecked exceptions, but it is not required.
26. How can an exception handler be written in Java so that it handles any exception?
The exception handlers of Java have the same form as those of C++, except that every catch must have a parameter and the class of the parameter must be a descendant of the predefined class Throwable. The syntax of the try construct in Java is exactly as that of C++, except for the finally clause.
28. What is the purpose of Java finally clause?
A finally clause is placed at the end of the list of handlers just after a complete try construct. The semantics of this construct is as follows: If the try clause throws no exceptions, the finally clause is executed before execution continues after the try construct. If the try clause throws an exception and it is caught by a following handler, the finally clause is executed after the handler completes its execution. If the try clause throws an exception but it is not caught by a handler following the try construct, the finally clause is executed before the exception is propagated
Problem Set
1 . What mechanism did early programming languages provide to detect or attempt to deal with errors?
Early programming languages were designed and implemented in such a way that the user program
could neither detect nor attempt to deal with such errors. In these languages, the occurrence of such an error simply causes the program to be terminated and control to be transferred to the operating system. The typical operating system reaction to a run-time error is to display a diagnostic message, which may be meaningful and therefore useful, or highly cryptic. After displaying the message, the program is terminated.
2. Describe the approach for the detection of subscript range errors used in C and Java.
Java compilers usually generate code to check the correctness of every subscript expression (they do not generate such code when it can be determined at compile time that a subscript expression cannot have an out-of-range value, for example, if the subscript is a literal).
In C, subscript ranges are not checked because the cost of such checking was (and still is) not believed to be worth the benefit of detecting such errors. In some compilers for some languages, subscript range checking can be selected (if not turned on by default) or turned off (if it is on by default) as desired in the program or in the command that executes the compiler.
5. From a textbook on FORTRAN, determine how exception handling is done in FORTRAN programs.
For example, a Fortran “Read” statement can intercept inputerrors and end-of-file conditions, both of which are detected by the input device hardware. In both cases, the Read statement can specify the label of some statement in the user program that deals with the condition. In the case of the end-of-file, it is clear that the condition is not always considered an error. In most cases, it is nothing more than a signal that one kind of processing is completed and another kind must begin. In spite of the obvious difference between end-of-file and events that are always errors, such as a failed input process, Fortran handles both situations with the same mechanism.
6. In languages without exception-handling facilities, it is common to have most subprograms include an “error” parameter, which can be set to some value representing “OK” or some other value representing “error in procedure”. What advantage does a linguistic exception-handling facility like that of Ada have over this method?
There are several advantages of a linguistic mechanism for handling exceptions, such as that found in Ada, over simply using a flag error parameter in all subprograms. One advantage is that the code to test the flag after every call is eliminated. Such testing makes programs longer and harder to read. Another advantage is that exceptions can be propagated farther than one level of control in a uniform and implicit way. Finally, there is the advantage that all programs use a uniform method for dealing with unusual circumstances, leading to enhanced readability.
7. In a language without exception handling facilities, we could send an error-handling procedure as a parameter to each procedure that can detect errors that must be handled. What disadvantages are there to this method?
There are several disadvantages of sending error handling subprograms to other subprograms. One is that it may be necessary to send several error handlers to some subprograms, greatly complicating both the writing and execution of calls. Another is that there is no method of propagating exceptions, meaning that they must all be handled locally. This complicates exception handling, because it requires more attention to handling in more places.
1. Define exception, exception handler, raising an exception, disabling an exception, continuation, finalization, and built-in exception.
An exception is an unusual event that is detectable by either hardware or software and that may require special processing. The special processing that may be required when an exception is detected is called exception handling. The processing is done by a code unit or segment called an exception handler. An exception is raised when its associated event occurs. In some situations, it may be desirable to ignore certain hardware-detectable exceptions—for example, division by zero—for a time. This action would be done by disabling the exception. After an exception handler executes, either control can transfer to somewhere in the program outside of the handler code or
Program execution can simply terminate. We term this the question of control continuation after handler execution, or simply continuation. In some situations, it is necessary to complete some computation regardless of how subprogram execution terminates. The ability to specify such a computation is called finalization. Built-in exceptions have a built-in meaning, it is generally inadvisable to use these to signal program-specific error conditions. Instead we introduce a new exception using an exception declaration, and signal it using a raise expression when a run-time violation occurs. That way we can associate specific exceptions with specific pieces of code, easing the process of tracking down the source of the error.
7. Where are unhandled exceptions propagated in Ada if raised in a subprogram?
A block? A package body? A task?
When an exception is raised in a block, in either its declarations or executable statements, and the block has no handler for it, the exception is propagated to the next larger enclosing static scope, which is the code that “called” it. The point to which the exception is propagated is just after the end of the block in which it occurred, which is its “return” point. When an exception is raised in a package body and the package body has no handler for the exception, the exception is propagated to the declaration section of the unit containing the package declaration. If the package happens to be a library unit (which is separately compiled), the program is terminated.
If an exception occurs at the outermost level in a task body (not in a nested block) and the task contains a handler for the exception, that handler is executed and the task is marked as being completed. If the task does not have a handler for the exception, the task is simply marked as being completed; the exception is not propagated. The control mechanism of a task is too complex to lend itself to a reasonable and simple answer to the question of where its unhandled exceptions should be propagated.
10. What are the four exceptions defined in the Standard package of Ada?
The four exception defined in the standard package of Ada are Constraint_Error, Program_Error, Storage_Error, Tasking_Error
11. What is the use of suppress pragma in Ada?
An Ada pragma is a directive to the compiler. Certain run-time checks that are parts of the built-in exceptions can be disabled in Ada programs by use of the Suppress pragma, the simple form of which is pragma Suppress(check_name)
where check_name is the name of a particular exception check. The Suppress pragma can appear only in declaration sections. When it appears, the specified check may be suspended in the associated block or program unit of which the declaration section is a part. Explicit raises are not affected by Suppress. Although it is not required, most Ada compilers implement the Suppress pragma.
13. Describe three problems with Ada’s exception handling.
There are several problems with Ada’s exception handling. One problem is the propagation model, which allows exceptions to be propagated to an outer scope in which the exception is not visible. Also, it is not always possible to determine the origin of propagated exceptions. Another problem is the inadequacy of exception handling for tasks. For example, a task that raises an exception but does not handle it simply dies. Finally, when support for object-oriented programming was added in Ada 95, its exception handling was not extended to deal with the new constructs. For example, when several objects of a class are created and used in a block and one of them propagates an exception, it is impossible to determine which one raised the exception.
14. What is the name of all C++ exception handlers?
Each catch function is an exception handler. A catch function can have only a single formal parameter, which is similar to a formal parameter in a function definition in C++, including the possibility of it being an ellipsis (. . .). A handler with an ellipsis formal parameter is the catch-all handler; it is enacted for any raised exception if no appropriate handler was found. The formal parameter also can be a naked type specifier, such as float, as in a function prototype. In such a case, the only purpose of the formal parameter is to make the handler uniquely identifiable. When information about the exception is to be passed to the handler, the formal parameter includes a variable name that is used for that purpose. Because the class of the parameter can be any user-defined class, the parameter can include as many data members as are
necessary.
15. Which standard libraries define and throw the exception out_of_range in C++?
The exception out_of_range in C++ thrown by library container classes
16. Which standard libraries define and throw the exception overflow_error in C++?
the exception overflow_error in C++ thrown by math library functions
19. State the similarity between the exception handling mechanism in C++ and Ada
In some ways, the C++ exception-handling mechanism is similar to that of Ada. For example, unhandled exceptions in functions are propagated to the function’s caller.
20. State the differences between the exception handling mechanism in C++ and Ada
There are no predefined hardware-detectable exceptions that can be handled by the user, and exceptions are not named. Exceptions are connected to handlers through a parameter type in which the formal parameter may be omitted. The type of the formal parameter of a handler determines the condition under which it is called but may have nothing whatsoever to do with the nature of the raised exception.
24. What is the difference between checked and unchecked exceptions in Java?
Exceptions of class Error and RuntimeException and their descendants are called unchecked exceptions. All other exceptions are called checked exceptions. Unchecked exceptions are never a concern of the compiler. However, the compiler ensures that all checked exceptions a method can throw are either listed in its throws clause or handled in the method. Note that checking this at compile time differs from C++, in which it is done at run time. The reason why exceptions of the classes Error and RuntimeException and their descendants are unchecked is that any method could throw them. A program can catch unchecked exceptions, but it is not required.
26. How can an exception handler be written in Java so that it handles any exception?
The exception handlers of Java have the same form as those of C++, except that every catch must have a parameter and the class of the parameter must be a descendant of the predefined class Throwable. The syntax of the try construct in Java is exactly as that of C++, except for the finally clause.
28. What is the purpose of Java finally clause?
A finally clause is placed at the end of the list of handlers just after a complete try construct. The semantics of this construct is as follows: If the try clause throws no exceptions, the finally clause is executed before execution continues after the try construct. If the try clause throws an exception and it is caught by a following handler, the finally clause is executed after the handler completes its execution. If the try clause throws an exception but it is not caught by a handler following the try construct, the finally clause is executed before the exception is propagated
Problem Set
1 . What mechanism did early programming languages provide to detect or attempt to deal with errors?
Early programming languages were designed and implemented in such a way that the user program
could neither detect nor attempt to deal with such errors. In these languages, the occurrence of such an error simply causes the program to be terminated and control to be transferred to the operating system. The typical operating system reaction to a run-time error is to display a diagnostic message, which may be meaningful and therefore useful, or highly cryptic. After displaying the message, the program is terminated.
2. Describe the approach for the detection of subscript range errors used in C and Java.
Java compilers usually generate code to check the correctness of every subscript expression (they do not generate such code when it can be determined at compile time that a subscript expression cannot have an out-of-range value, for example, if the subscript is a literal).
In C, subscript ranges are not checked because the cost of such checking was (and still is) not believed to be worth the benefit of detecting such errors. In some compilers for some languages, subscript range checking can be selected (if not turned on by default) or turned off (if it is on by default) as desired in the program or in the command that executes the compiler.
5. From a textbook on FORTRAN, determine how exception handling is done in FORTRAN programs.
For example, a Fortran “Read” statement can intercept inputerrors and end-of-file conditions, both of which are detected by the input device hardware. In both cases, the Read statement can specify the label of some statement in the user program that deals with the condition. In the case of the end-of-file, it is clear that the condition is not always considered an error. In most cases, it is nothing more than a signal that one kind of processing is completed and another kind must begin. In spite of the obvious difference between end-of-file and events that are always errors, such as a failed input process, Fortran handles both situations with the same mechanism.
6. In languages without exception-handling facilities, it is common to have most subprograms include an “error” parameter, which can be set to some value representing “OK” or some other value representing “error in procedure”. What advantage does a linguistic exception-handling facility like that of Ada have over this method?
There are several advantages of a linguistic mechanism for handling exceptions, such as that found in Ada, over simply using a flag error parameter in all subprograms. One advantage is that the code to test the flag after every call is eliminated. Such testing makes programs longer and harder to read. Another advantage is that exceptions can be propagated farther than one level of control in a uniform and implicit way. Finally, there is the advantage that all programs use a uniform method for dealing with unusual circumstances, leading to enhanced readability.
7. In a language without exception handling facilities, we could send an error-handling procedure as a parameter to each procedure that can detect errors that must be handled. What disadvantages are there to this method?
There are several disadvantages of sending error handling subprograms to other subprograms. One is that it may be necessary to send several error handlers to some subprograms, greatly complicating both the writing and execution of calls. Another is that there is no method of propagating exceptions, meaning that they must all be handled locally. This complicates exception handling, because it requires more attention to handling in more places.
Concepts of Programming Languages Assignment - Chapter 13
Review Questions
1. What are the three possible levels of concurrency in programs?
Concurrency in software execution can occur at four different levels: instruction level (executing two or more machine instructions simultaneously), statement level (executing two or more high-level language statements simultaneously), unit level (executing two or more subprogram units simultaneously), and program level (executing two or more programs simultaneously).
2. Describe the logical architecture of an SIMD computer.
In an SIMD computer, each processor has its own local memory. One processor controls the operation of the other processors. Because all of the processors, except the controller, execute the same instruction at the same time, no synchronization is required in the software. Perhaps the most widely used
SIMD machines are a category of machines called vector processors. They have groups of registers that store the operands of a vector operation in which the same instruction is executed on the whole group of operands simultaneously. Originally, the kinds of programs that could most benefit from this architecture were in scientific computation, an area of computing that is often the target of multiprocessor machines. However, SIMD processors are now used for a variety of application areas, among them graphics and video processing. Until recently, most supercomputers were vector processors.
3. Describe the logical architecture of an MIMD computer.
Computers that have multiple processors that operate independently but whose operations can be synchronized are called Multiple-Instruction Multiple- Data (MIMD) computers. Each processor in an MIMD computer executes its own instruction stream. MIMD computers can appear in two distinct configurations: distributed and shared memory systems. The distributed MIMD machines, in which each processor has its own memory, can be either built in a single chassis or distributed, perhaps over a large area. The shared-memory MIMD machines obviously must provide some means of synchronization to prevent memory access clashes. Even distributed MIMD machines require synchronization to operate together on single programs. MIMD computers, which are more general than SIMD computers, support unit-level concurrency. The primary focus of this chapter is on language design for shared memory MIMD computers, which are often called multiprocessors.
4. What level of program concurrency is best supported by SIMD computers?
Statement-level concurrency
5. What level of program concurrency is best supported by SIMD computers?
Unit-level concurrency
6. Describe the logical architecture of a vector processor.
Vector processor have groups of registers that store the operands of a vector operation in which the same instruction is executed on the whole group of operands simultaneously. Originally, the kinds of programs that could most benefit from this architecture were in scientific computation, an area of computing that is often the target of multiprocessor machines.
7. What is the difference between physical and logical concurrency?
There are two distinct categories of concurrent unit control. The most natural category of concurrency is that in which, assuming that more than one processor is available, several program units from the same program literally execute simultaneously. This is physical concurrency. A slight relaxation of this concept of concurrency allows the programmer and the application software to assume that there are multiple processors providing actual concurrency, when in fact the actual execution of programs is taking place in interleaved fashion on a single processor. This is logical concurrency.
8. what is the work of a scheduler?
A run-time system program called a scheduler manages the sharing of processors among the tasks.
34. What does the Java sleep method do?
The sleep method has a single parameter, which is the integer number of milliseconds that the caller of sleep wants the thread to be blocked. After the specified number of milliseconds has passed, the thread will be put in the task-ready queue. Because there is no way to know how long a thread will be in the task-ready queue before it runs, the parameter to sleep is the minimum amount of time the thread will not be in execution. The sleep method can throw an InterruptedException, which must be handled in the method that calls sleep.
35. what does the Java yield method do?
The yield method, which takes no parameters, is a request from the running thread to surrender the processor voluntarily. The thread is put immediately in the task-ready queue, making it ready to run. The scheduler then chooses the highest-priority thread from the task-ready queue. If there are no other ready threads with priority higher than the one that just yielded the processor, it may also be the next thread to get the processor.
36. what does the Java join method do?
The join method is used to force a method to delay its execution until the run method of another thread has completed its execution. join is used when the processing of a method cannot continue until the work of the other thread is complete.
37. What does the Java interrupt method do?
The interrupt method is one way to communicate to a thread that it should stop. This method does not stop the thread; rather, it sends the thread a message that actually just sets a bit in the thread object, which can be checked by the thread. The bit is checked with the predicate method, isInterrupted. This is not a complete solution, because the thread one is attempting to interrupt may be sleeping or waiting at the time the interrupt method is called, which means that it will not be checking to see if it has been interrupted. For these situations, the interrupt method also throws an exception, InterruptedException, which also causes the thread to awaken (from sleeping or waiting). So, a thread can periodically check to see whether it has been interrupted and if so, whether it can terminate. The thread cannot miss the interrupt, because if it was asleep or waiting when the interrupt occurred, it
will be awakened by the interrupt.
42. What kind of Java object is a monitor?
In Java, a monitor can be implemented in a class designed as an abstract data type, with the shared data being the type. Accesses to objects of the class are controlled by adding the synchronized modifier to the access methods.
47. How are explicit locks supported in Java?
Java 5.0 introduced explicit locks as an alternative to synchronized method and blocks, which provide implicit locks. The Lock interface declares the lock, unlock, and tryLock methods. The predefined ReentrantLock class implements the Lock interface. To lock a block of code, the following idiom can be used:
Lock lock = new ReentrantLock();
. . .
Lock.lock();
try {
// The code that accesses the shared data
} finally {
Lock.unlock();
}
48. What kinds of methods can run in a C# thread?
Rather than just methods named run, as in Java, any C# method can run in its own thread.
55. What is Concurrent ML?
Concurrent ML (CML) is an extension to ML that includes a form of threads and a form of synchronous message passing to support concurrency. The language is completely described in Reppy (1999).
59. Who developed the monitor concept?
The monitor concept is developed and its implementation in Concurrent Pascal is described by Brinch Hansen (1977)
Problem Set
1 . Explain why a race condition can create problems for a system.
a race condition creates problem because when a race condition happens two or more tasks are racing to use the shared resource and the behavior of the program depends on which task arrives first (and wins the race).
2. What are the different ways to handle deadlock?
When deadlock occurs, assuming that only two program units are causing the deadlock, one of the involved program units should be gracefully terminated, thereby allowed the other to continue.
3. Busy waiting is a method whereby a task waits for a given event by continuously checking for that event to occur. What is the main problem with this approach?
The main problem with busy waiting is that machine cycles are wasted in the process.
4. In the producer-consumer example of Section 13.3, suppose that we incorrectly replaced the release(access) in the consumer process with wait(access). What woud be the result of this error on execution of the system?
Deadlock would occur if the release(access) were replaced by a wait(access) in the consumer process, because instead of relinquishing access control, the consumer would wait for control that it already had.
1. What are the three possible levels of concurrency in programs?
Concurrency in software execution can occur at four different levels: instruction level (executing two or more machine instructions simultaneously), statement level (executing two or more high-level language statements simultaneously), unit level (executing two or more subprogram units simultaneously), and program level (executing two or more programs simultaneously).
2. Describe the logical architecture of an SIMD computer.
In an SIMD computer, each processor has its own local memory. One processor controls the operation of the other processors. Because all of the processors, except the controller, execute the same instruction at the same time, no synchronization is required in the software. Perhaps the most widely used
SIMD machines are a category of machines called vector processors. They have groups of registers that store the operands of a vector operation in which the same instruction is executed on the whole group of operands simultaneously. Originally, the kinds of programs that could most benefit from this architecture were in scientific computation, an area of computing that is often the target of multiprocessor machines. However, SIMD processors are now used for a variety of application areas, among them graphics and video processing. Until recently, most supercomputers were vector processors.
3. Describe the logical architecture of an MIMD computer.
Computers that have multiple processors that operate independently but whose operations can be synchronized are called Multiple-Instruction Multiple- Data (MIMD) computers. Each processor in an MIMD computer executes its own instruction stream. MIMD computers can appear in two distinct configurations: distributed and shared memory systems. The distributed MIMD machines, in which each processor has its own memory, can be either built in a single chassis or distributed, perhaps over a large area. The shared-memory MIMD machines obviously must provide some means of synchronization to prevent memory access clashes. Even distributed MIMD machines require synchronization to operate together on single programs. MIMD computers, which are more general than SIMD computers, support unit-level concurrency. The primary focus of this chapter is on language design for shared memory MIMD computers, which are often called multiprocessors.
4. What level of program concurrency is best supported by SIMD computers?
Statement-level concurrency
5. What level of program concurrency is best supported by SIMD computers?
Unit-level concurrency
6. Describe the logical architecture of a vector processor.
Vector processor have groups of registers that store the operands of a vector operation in which the same instruction is executed on the whole group of operands simultaneously. Originally, the kinds of programs that could most benefit from this architecture were in scientific computation, an area of computing that is often the target of multiprocessor machines.
7. What is the difference between physical and logical concurrency?
There are two distinct categories of concurrent unit control. The most natural category of concurrency is that in which, assuming that more than one processor is available, several program units from the same program literally execute simultaneously. This is physical concurrency. A slight relaxation of this concept of concurrency allows the programmer and the application software to assume that there are multiple processors providing actual concurrency, when in fact the actual execution of programs is taking place in interleaved fashion on a single processor. This is logical concurrency.
8. what is the work of a scheduler?
A run-time system program called a scheduler manages the sharing of processors among the tasks.
34. What does the Java sleep method do?
The sleep method has a single parameter, which is the integer number of milliseconds that the caller of sleep wants the thread to be blocked. After the specified number of milliseconds has passed, the thread will be put in the task-ready queue. Because there is no way to know how long a thread will be in the task-ready queue before it runs, the parameter to sleep is the minimum amount of time the thread will not be in execution. The sleep method can throw an InterruptedException, which must be handled in the method that calls sleep.
35. what does the Java yield method do?
The yield method, which takes no parameters, is a request from the running thread to surrender the processor voluntarily. The thread is put immediately in the task-ready queue, making it ready to run. The scheduler then chooses the highest-priority thread from the task-ready queue. If there are no other ready threads with priority higher than the one that just yielded the processor, it may also be the next thread to get the processor.
36. what does the Java join method do?
The join method is used to force a method to delay its execution until the run method of another thread has completed its execution. join is used when the processing of a method cannot continue until the work of the other thread is complete.
37. What does the Java interrupt method do?
The interrupt method is one way to communicate to a thread that it should stop. This method does not stop the thread; rather, it sends the thread a message that actually just sets a bit in the thread object, which can be checked by the thread. The bit is checked with the predicate method, isInterrupted. This is not a complete solution, because the thread one is attempting to interrupt may be sleeping or waiting at the time the interrupt method is called, which means that it will not be checking to see if it has been interrupted. For these situations, the interrupt method also throws an exception, InterruptedException, which also causes the thread to awaken (from sleeping or waiting). So, a thread can periodically check to see whether it has been interrupted and if so, whether it can terminate. The thread cannot miss the interrupt, because if it was asleep or waiting when the interrupt occurred, it
will be awakened by the interrupt.
42. What kind of Java object is a monitor?
In Java, a monitor can be implemented in a class designed as an abstract data type, with the shared data being the type. Accesses to objects of the class are controlled by adding the synchronized modifier to the access methods.
47. How are explicit locks supported in Java?
Java 5.0 introduced explicit locks as an alternative to synchronized method and blocks, which provide implicit locks. The Lock interface declares the lock, unlock, and tryLock methods. The predefined ReentrantLock class implements the Lock interface. To lock a block of code, the following idiom can be used:
Lock lock = new ReentrantLock();
. . .
Lock.lock();
try {
// The code that accesses the shared data
} finally {
Lock.unlock();
}
48. What kinds of methods can run in a C# thread?
Rather than just methods named run, as in Java, any C# method can run in its own thread.
55. What is Concurrent ML?
Concurrent ML (CML) is an extension to ML that includes a form of threads and a form of synchronous message passing to support concurrency. The language is completely described in Reppy (1999).
59. Who developed the monitor concept?
The monitor concept is developed and its implementation in Concurrent Pascal is described by Brinch Hansen (1977)
Problem Set
1 . Explain why a race condition can create problems for a system.
a race condition creates problem because when a race condition happens two or more tasks are racing to use the shared resource and the behavior of the program depends on which task arrives first (and wins the race).
2. What are the different ways to handle deadlock?
When deadlock occurs, assuming that only two program units are causing the deadlock, one of the involved program units should be gracefully terminated, thereby allowed the other to continue.
3. Busy waiting is a method whereby a task waits for a given event by continuously checking for that event to occur. What is the main problem with this approach?
The main problem with busy waiting is that machine cycles are wasted in the process.
4. In the producer-consumer example of Section 13.3, suppose that we incorrectly replaced the release(access) in the consumer process with wait(access). What woud be the result of this error on execution of the system?
Deadlock would occur if the release(access) were replaced by a wait(access) in the consumer process, because instead of relinquishing access control, the consumer would wait for control that it already had.
Concepts of Programming Languages Assignment - Chapter 12
Review Questions
4. What is message protocol?
Message protocol is the entire collection of methods of an object.
5. What is an overriding method?
Overriding method is method that overrides the inherited method.
7. What is dynamic dispatch?
Dynamic dispatch is the third characteristic (after abstract data types and inheritance) of object-oriented programming language which is a kind of polymorhphism provided by the dynamic binding of messages to method definitions.
12. From where are Smalltalk objects allocated?
Smalltalk objects are allocated from the heap and are referenced through reference variables, which are implicitly dereferenced.
15. What kind of inheritance, single or multiple, does Smalltalk support?
Smalltalk supports single inheritance; it does not allow multiple inheritance.
19. How are C++ heap-allocated objects deallocated?
C++ heap-allocated objects are deallocated using destructor.
29. Does Objective-C support multiple inheritance?
No Objective-C doesn’t support it. (It supports only single inheritance).
33. What is the purpose of an Objective-C category?
The purpose of an Objective-C category is to add certain functionalities to different classes and also to provide some of the benefits of multiple inheritance, without the naming collisions that could occur if modules did not require module names on their functions.
38. What is boxing?
Boxing is primitive values in Java 5.0+ which is implicitly coerced when they are put in object context. This coercion converts the primitive value to an object of the wrapper class of the primitive value’s type.
39. How are Java objects deallocated?
By implicitly calling a finalizemethod when the garbage collector is about to reclaim the storage occupied by the object.
Problem Set
3. Compare the inheritance of C++ and Java.
- In Java, all classes inherit from the Object class directly or indirectly. Therefore, there is always a single inheritance tree of classes in Java, and Object class is root of the tree. In Java, if we create a class that doesn’t inherit from any class then it automatically inherits from Object Class. In C++, there is forest of classes; when we create a class that doesn’t inherit from anything, we create a new tree in forest.
- In Java, members of the grandparent class are not directly accessible.
- The meaning of protected member access specifier is somewhat different in Java. In Java, protected members of a class “A” are accessible in other class “B” of same package, even if B doesn’t inherit from A (they both have to be in the same package)
- Java uses extends keyword for inheritence. Unlike C++, Java doesn’t provide an inheritance specifier like public, protected or private. Therefore, we cannot change the protection level of members of base class in Java, if some data member is public or protected in base class then it remains public or protected in derived class. Like C++, private members of base class are not accessible in derived class.
Unlike C++, in Java, we don’t have to remember those rules of inheritance which are combination of base class access specifier and inheritance specifier.
- In Java, methods are virtual by default. In C++, we explicitly use virtual keyword.
- Java uses a separate keyword interface for interfaces, and abstract keyword for abstract classes and abstract functions.
- Unlike C++, Java doesn’t support multiple inheritance. A class cannot inherit from more than one class. A class can implement multiple interfaces though.
– In C++, default constructor of parent class is automatically called, but if we want to call parametrized constructor of a parent class, we must use Initalizer list. Like C++, default constructor of the parent class is automatically called in Java, but if we want to call parametrized constructor then we must use super to call the parent constructor
5. Compare abstract class and interface in Java.
- First and major difference between abstract class and interface is that, abstract class is a class while interface is a interface, means by extending abstract class you can not extend another class becauseJava does not support multiple inheritance but you can implement multiple inheritance in Java.
- Second difference between interface and abstract class in Java is that you can not create non abstract method in interface, every method in interface is by default abstract, but you can create non abstract method in abstract class. Even a class which doesn’t contain any abstract method can be abstract by using abstract keyword.
- Third difference between abstract class and interface in Java is that abstract class are slightly faster than interface because interface involves a search before calling any overridden method in Java. This is not a significant difference in most of cases but if you are writing a time critical application than you may not want to leave any stone unturned.
- Fourth difference between abstract class vs interface in Java is that, interface are better suited for Type declaration and abstract class is more suited for code reuse and evolution perspective.
- Another notable difference between interface and abstract class is that when you add a new method in existing interface it breaks all its implementation and you need to provide an implementation in all clients which is not good. By using abstract class you can provide default implementation in super class.
7. What is one programming situation where multiple inheritance has a significant disadvantage over interfaces?
A situation when there are two classes derived from a common parent and those two derived class has one child.
9. Give an example of inheritance in C++, where a subclass overrides the superclass methods.
class plan{
public:
void fly(){
cout << “fly” << endl;
}
};
class jet:public class plan{
public:
void fly()
{
cout << “Fly! Rocket jet activated!” << endl;
}
}
10. Explain one advantage of inheritance.
Inheritance offers a solution to both the modification problem posed by abstract data type reuse and the program organization problem. If a new abstract data type can inherit the data and functionality of some existing type, and is also allowed to modify some of those entities and add new entities, reuse and is also allowed to modify some of those entities and add new entities, reuse is greatly facilitated without requiring change to the reused abstract data type. Programmers can begin with an existing abstract data type and design a modified descendant of it to fit a new problem requirement. Furthermore, inheritance provides a framework for the definition of hierarchies of related classes that can reflect the descendant relationship in the problem space.
12. Compare inheritance and nested classes in C++. Which of these supports an is-a relationship?
Inheritance is where one class (child class) inherits the members of another class (parent class).Nested class is a class declared entirely within the body of another class or interface.
Inheritance does.
17. What are the different options for object destruction in Java?
There is no explicit deallocation operator. A finalize method is implicitly called when the garbage collector is about to reclaim the storage occupied by the object.
4. What is message protocol?
Message protocol is the entire collection of methods of an object.
5. What is an overriding method?
Overriding method is method that overrides the inherited method.
7. What is dynamic dispatch?
Dynamic dispatch is the third characteristic (after abstract data types and inheritance) of object-oriented programming language which is a kind of polymorhphism provided by the dynamic binding of messages to method definitions.
12. From where are Smalltalk objects allocated?
Smalltalk objects are allocated from the heap and are referenced through reference variables, which are implicitly dereferenced.
15. What kind of inheritance, single or multiple, does Smalltalk support?
Smalltalk supports single inheritance; it does not allow multiple inheritance.
19. How are C++ heap-allocated objects deallocated?
C++ heap-allocated objects are deallocated using destructor.
29. Does Objective-C support multiple inheritance?
No Objective-C doesn’t support it. (It supports only single inheritance).
33. What is the purpose of an Objective-C category?
The purpose of an Objective-C category is to add certain functionalities to different classes and also to provide some of the benefits of multiple inheritance, without the naming collisions that could occur if modules did not require module names on their functions.
38. What is boxing?
Boxing is primitive values in Java 5.0+ which is implicitly coerced when they are put in object context. This coercion converts the primitive value to an object of the wrapper class of the primitive value’s type.
39. How are Java objects deallocated?
By implicitly calling a finalizemethod when the garbage collector is about to reclaim the storage occupied by the object.
Problem Set
3. Compare the inheritance of C++ and Java.
- In Java, all classes inherit from the Object class directly or indirectly. Therefore, there is always a single inheritance tree of classes in Java, and Object class is root of the tree. In Java, if we create a class that doesn’t inherit from any class then it automatically inherits from Object Class. In C++, there is forest of classes; when we create a class that doesn’t inherit from anything, we create a new tree in forest.
- In Java, members of the grandparent class are not directly accessible.
- The meaning of protected member access specifier is somewhat different in Java. In Java, protected members of a class “A” are accessible in other class “B” of same package, even if B doesn’t inherit from A (they both have to be in the same package)
- Java uses extends keyword for inheritence. Unlike C++, Java doesn’t provide an inheritance specifier like public, protected or private. Therefore, we cannot change the protection level of members of base class in Java, if some data member is public or protected in base class then it remains public or protected in derived class. Like C++, private members of base class are not accessible in derived class.
Unlike C++, in Java, we don’t have to remember those rules of inheritance which are combination of base class access specifier and inheritance specifier.
- In Java, methods are virtual by default. In C++, we explicitly use virtual keyword.
- Java uses a separate keyword interface for interfaces, and abstract keyword for abstract classes and abstract functions.
- Unlike C++, Java doesn’t support multiple inheritance. A class cannot inherit from more than one class. A class can implement multiple interfaces though.
– In C++, default constructor of parent class is automatically called, but if we want to call parametrized constructor of a parent class, we must use Initalizer list. Like C++, default constructor of the parent class is automatically called in Java, but if we want to call parametrized constructor then we must use super to call the parent constructor
5. Compare abstract class and interface in Java.
- First and major difference between abstract class and interface is that, abstract class is a class while interface is a interface, means by extending abstract class you can not extend another class becauseJava does not support multiple inheritance but you can implement multiple inheritance in Java.
- Second difference between interface and abstract class in Java is that you can not create non abstract method in interface, every method in interface is by default abstract, but you can create non abstract method in abstract class. Even a class which doesn’t contain any abstract method can be abstract by using abstract keyword.
- Third difference between abstract class and interface in Java is that abstract class are slightly faster than interface because interface involves a search before calling any overridden method in Java. This is not a significant difference in most of cases but if you are writing a time critical application than you may not want to leave any stone unturned.
- Fourth difference between abstract class vs interface in Java is that, interface are better suited for Type declaration and abstract class is more suited for code reuse and evolution perspective.
- Another notable difference between interface and abstract class is that when you add a new method in existing interface it breaks all its implementation and you need to provide an implementation in all clients which is not good. By using abstract class you can provide default implementation in super class.
7. What is one programming situation where multiple inheritance has a significant disadvantage over interfaces?
A situation when there are two classes derived from a common parent and those two derived class has one child.
9. Give an example of inheritance in C++, where a subclass overrides the superclass methods.
class plan{
public:
void fly(){
cout << “fly” << endl;
}
};
class jet:public class plan{
public:
void fly()
{
cout << “Fly! Rocket jet activated!” << endl;
}
}
10. Explain one advantage of inheritance.
Inheritance offers a solution to both the modification problem posed by abstract data type reuse and the program organization problem. If a new abstract data type can inherit the data and functionality of some existing type, and is also allowed to modify some of those entities and add new entities, reuse and is also allowed to modify some of those entities and add new entities, reuse is greatly facilitated without requiring change to the reused abstract data type. Programmers can begin with an existing abstract data type and design a modified descendant of it to fit a new problem requirement. Furthermore, inheritance provides a framework for the definition of hierarchies of related classes that can reflect the descendant relationship in the problem space.
12. Compare inheritance and nested classes in C++. Which of these supports an is-a relationship?
Inheritance is where one class (child class) inherits the members of another class (parent class).Nested class is a class declared entirely within the body of another class or interface.
Inheritance does.
17. What are the different options for object destruction in Java?
There is no explicit deallocation operator. A finalize method is implicitly called when the garbage collector is about to reclaim the storage occupied by the object.
Concepts of Programming Languages Assignment - Chapter 11
Review question
2. Define abstract data type.
data type that satisfies the following conditions:
-The representation of objects of the type is hidden from the program units that use the type, so the only direct operations possible on those objects are those provided in the type’s definition.
-The declarations of the type and the protocols of the operations on objects of the type, which provide the type’s interface, are contained in a single syntactic unit. The type’s interface does not depend on the representation of the objects or the implementation of the operations. Also, other program units are allowed to create variables of the defined type.
8. What is the difference between private and limited private types in Ada?
Limited private is more restricted form and objects of a type that is declared limited private have no built-in operations.
10. What is the use of the Ada with clause?
With clause makes the names defined in external packages visible; in this case Ada. Text_IO, which provides functions for input of text.
11. What is the use of the Ada use clause?
The with clause makes the names defined in external packages Visible.
12. What is the fundamental difference between a C++ class and an Ada package?
Ada packages are more generalize encapsulations that can define any number of types.
15. What is the purpose of a C++ destructor?
The purpose of a C++ desctructor is as a debugging aid, in which case they simply display or print the values of some or all of the object’s data members before those members are deallocated.
16. What are the legal return types of a desctructor?
Destructor has no return types and doesn’t use return statements.
20. What is the use of limited private types?
An alternative to private types is a more restricted form: limited private types. Nonpointer limited private types are described in the private section of a package specification, as are nonpointer private types. The only syntactic difference is that limited private types are declared to be limited private in the visible part of the package specification. The semantic difference is that objects of a type that is declared limited private have no built-in operations. Such a type is useful when the usual predefined operations of assignment and comparison are not meaningful or useful. For example, assignment and comparison are rarely used for stacks.
21. What are initializers in Objective-C?
The initializers in Objective-C are constructors.
22. What is the use of @private and @public directives?
The use is to specify the access levels of the instance variables in a class definition.
27. Where are all Java methods defined?
All Java methods are defined in a class.
30. What is a friend function? What is a friend class?
a “friend” of a given class is allowed access to public, private, or protected data in that class. Normally, function that is defined outside of a class cannot access such information.
Class that can access the private and protected members of the class in which it is declared as a friend. On declaration of friend class all member function of the friend class become friends of the class in which the friend class was declared.
Problem set
4. What are the advantages of the nonpointer concept in Java?
Any task that would require arrays, structures, and pointers in C can be more easily and reliably performed by declaring objects and arrays of objects. Instead of complex pointer manipulation on array pointers, you access arrays by their arithmetic indices. The Java run-time system checks all array indexing to ensure indices are within the bounds of the array. You no longer have dangling pointers and trashing of memory because of incorrect pointers, because there are no pointers in Java.
10. Which two conditions make data type “abstract”?
The representation of objects of the type is hidden from the program units that use the type, so the only direct operations possible on those objects are those provided in the type’s definition.
The declarations of the type and the protocols of the operations on objects of the type, which provide the type’s interface, are contained in a single syntactic unit. The type’s interface does not depend on the representation of the objects or the implementation of the operations. Also, other program units are allowed to create variables of the defined type.
12. How are classes in Ruby made dynamic?
Classes in Ruby are dynamic in the sense that members can be added at any time. This is done by simply including additional class definitions that specify the new members. Moreover, even predefined classes of the language, such as String, can be extended.
13. Compare and contrast the data abstraction of Java and C++.
Java support for abstract data types is similar to that of C++. There are, however, a few important differences. All objects are allocated from the heap and accessed through reference variables. Methods in Java must be defined completely in a class. A method body must appear with its corresponding method
header. Therefore, a Java abstract data type is both declared and defined in a single syntactic unit. A Java compiler can inline any method that is not overridden. Definitions are hidden from clients by declaring them to be private. Rather than having private and public clauses in its class definitions, in Java access modifiers can be attached to method and variable definitions. If an instance variable or method does not have an access modifier, it has package access.
19. Compare Java’s packages with Ruby’s modules.
In Ruby, the require statement is used to import a package or a module. For example, the extensions package/module is imported as follows.
require ‘extensions’
External files may be included in a Ruby application by using load or require. For example, to include the external file catalog.rb, add the following require statement.
require “catalog.rb”
The difference between load and require is that load includes the specified Ruby file every time the method is executed and require includes the Ruby file only once.
In Java, the import statement is used to load a package. For example, a Java package java.sql is loaded as follows.
import java.sql.*;
2. Define abstract data type.
data type that satisfies the following conditions:
-The representation of objects of the type is hidden from the program units that use the type, so the only direct operations possible on those objects are those provided in the type’s definition.
-The declarations of the type and the protocols of the operations on objects of the type, which provide the type’s interface, are contained in a single syntactic unit. The type’s interface does not depend on the representation of the objects or the implementation of the operations. Also, other program units are allowed to create variables of the defined type.
8. What is the difference between private and limited private types in Ada?
Limited private is more restricted form and objects of a type that is declared limited private have no built-in operations.
10. What is the use of the Ada with clause?
With clause makes the names defined in external packages visible; in this case Ada. Text_IO, which provides functions for input of text.
11. What is the use of the Ada use clause?
The with clause makes the names defined in external packages Visible.
12. What is the fundamental difference between a C++ class and an Ada package?
Ada packages are more generalize encapsulations that can define any number of types.
15. What is the purpose of a C++ destructor?
The purpose of a C++ desctructor is as a debugging aid, in which case they simply display or print the values of some or all of the object’s data members before those members are deallocated.
16. What are the legal return types of a desctructor?
Destructor has no return types and doesn’t use return statements.
20. What is the use of limited private types?
An alternative to private types is a more restricted form: limited private types. Nonpointer limited private types are described in the private section of a package specification, as are nonpointer private types. The only syntactic difference is that limited private types are declared to be limited private in the visible part of the package specification. The semantic difference is that objects of a type that is declared limited private have no built-in operations. Such a type is useful when the usual predefined operations of assignment and comparison are not meaningful or useful. For example, assignment and comparison are rarely used for stacks.
21. What are initializers in Objective-C?
The initializers in Objective-C are constructors.
22. What is the use of @private and @public directives?
The use is to specify the access levels of the instance variables in a class definition.
27. Where are all Java methods defined?
All Java methods are defined in a class.
30. What is a friend function? What is a friend class?
a “friend” of a given class is allowed access to public, private, or protected data in that class. Normally, function that is defined outside of a class cannot access such information.
Class that can access the private and protected members of the class in which it is declared as a friend. On declaration of friend class all member function of the friend class become friends of the class in which the friend class was declared.
Problem set
4. What are the advantages of the nonpointer concept in Java?
Any task that would require arrays, structures, and pointers in C can be more easily and reliably performed by declaring objects and arrays of objects. Instead of complex pointer manipulation on array pointers, you access arrays by their arithmetic indices. The Java run-time system checks all array indexing to ensure indices are within the bounds of the array. You no longer have dangling pointers and trashing of memory because of incorrect pointers, because there are no pointers in Java.
10. Which two conditions make data type “abstract”?
The representation of objects of the type is hidden from the program units that use the type, so the only direct operations possible on those objects are those provided in the type’s definition.
The declarations of the type and the protocols of the operations on objects of the type, which provide the type’s interface, are contained in a single syntactic unit. The type’s interface does not depend on the representation of the objects or the implementation of the operations. Also, other program units are allowed to create variables of the defined type.
12. How are classes in Ruby made dynamic?
Classes in Ruby are dynamic in the sense that members can be added at any time. This is done by simply including additional class definitions that specify the new members. Moreover, even predefined classes of the language, such as String, can be extended.
13. Compare and contrast the data abstraction of Java and C++.
Java support for abstract data types is similar to that of C++. There are, however, a few important differences. All objects are allocated from the heap and accessed through reference variables. Methods in Java must be defined completely in a class. A method body must appear with its corresponding method
header. Therefore, a Java abstract data type is both declared and defined in a single syntactic unit. A Java compiler can inline any method that is not overridden. Definitions are hidden from clients by declaring them to be private. Rather than having private and public clauses in its class definitions, in Java access modifiers can be attached to method and variable definitions. If an instance variable or method does not have an access modifier, it has package access.
19. Compare Java’s packages with Ruby’s modules.
In Ruby, the require statement is used to import a package or a module. For example, the extensions package/module is imported as follows.
require ‘extensions’
External files may be included in a Ruby application by using load or require. For example, to include the external file catalog.rb, add the following require statement.
require “catalog.rb”
The difference between load and require is that load includes the specified Ruby file every time the method is executed and require includes the Ruby file only once.
In Java, the import statement is used to load a package. For example, a Java package java.sql is loaded as follows.
import java.sql.*;
Concepts of Programming Languages Assignment - Chapter 10
Review Questions
1. What are the two reasons why implementing subprograms with stack-dynamic local variables is more difficult than implementing simple sub-programs?
The Format, or layout, of the non-code part of a subprogram is called an activation record.
An activation record stores all the information about subprogram calls, activation records stores the following data (in the following order)
A static chain is a chain of static links that connects certain activation record instances
Static_depth is an integer associated with a static scope representing the scope’s nesting depth
The chain_offset or nesting_depth of a non-local reference is the difference between the static_depth of the reference and that of the scope where it is declared
6. What are the two potential problems with the static chain methods?
One alternative to static chain is to use a display, for this approach, the static links are collected in a single array called a display. Display uses a pointer array to store the activation records along the static chain.
10. Explain the two methods of implementing block?
Blocks are treated as parameter less subprograms that are always called from the same place in the program.
Block can also be implemented in a different and somewhat simpler and more efficient way. The maximum amount of storage required for block variables at any time during the exaction of program can be statically determined, because block are entered and exited in strictly textual order.
11. Describe the deep access method of implementing dynamic scoping?
Deep Access – nonlocal references are found by searching the activation record instances on the dynamic chain. Length of chain cannot be statically determined every activation record instance must have variable names
12. Describe the shallow access method of implementing dynamic scoping?
In case of shallow access names and values are stored in a global table. Using this method, space is allocated for every variable name that is in the program (one space for variable temp though there might be several declarations of temp in the different methods). When a sub-routine is called it saves the current value of the variable and replaces it with the value in its current scope and restores the value of the variable while exiting.
14. Compare the efficiency of the deep access method to that of the shallow access method, in term of both call and nonlocal access?
The deep access methods provides fast subprogram linkage, but references to nonlocal, especially references to distant nonlocals (in term of the call chain), are costly. The shallow access methods provide much faster references to nonlocals, especially distant nonlocals, but are more costly in term of subprogram linkage.
Problem Set
7. It stated in this chapter that when nonlocal variables are accessed in a dynamic-scoped language using the dynamic chain, variable names must be stored in the activation records with the values. If this were actually done, every nonlocal access would require a sequence of costly string comparisons on names. Design an alternative to these string comparisons that would be faster.
One very simple alternative is to assign integer values to all variable names used in the program. Then the integer values could be used in the activation records, and the comparisons would be between integer values, which are much faster than string comparisons.
8. Pascal allows gotos with nonlocal targets. How could such statements be handled if static chains were used for nonlocal variable access?
Following the hint stated with the question, the target of every goto in a program could be represented as an address and a nesting_depth, where the nesting_depth is the difference between the nesting level of the procedure that contains the goto and that of the procedure containing the target. Then, when a goto is executed, the static chain is followed by the number of links indicated in the nesting_depth of the goto target. The stack top pointer is reset to the top of the activation record at the end of the chain.
9. The static-chain method could be expanded slightly by using two static links in each activation record instance where the second points to the static grandparent activation record instance. How would this approach affect the time required for subprogram linkage and nonlocal references?
Including two static links would reduce the access time to nonlocals that are defined in scopes two steps away to be equal to that for nonlocals that are one step away. Overall, because most nonlocal references are relatively close, this could significantly increase the execution efficiency of many programs.
11. If a compiler uses the static chain approach to implementing blocks, which of the entries in the activation records for subprograms are needed in the activation records for blocks?
There are two options for implementing blocks as parameterless subprograms: One way is to use the same activation record as a subprogram that has no parameters. This is the most simple way, because accesses to block variables will be exactly like accesses to local variables. Of course, the space for the static and dynamic links and the return address will be wasted. The alternative is to leave out the static and dynamic links and the return address, which saves space but makes accesses to block variables different from subprogram locals.
1. What are the two reasons why implementing subprograms with stack-dynamic local variables is more difficult than implementing simple sub-programs?
- A stack-dynamic local variable is more complex activation records. The compiler must generate code to cause implicit allocation and de-allocation of local variables
- Recursion must be supported (adds the possibility of multiple simultaneous activations of a subprogram).
The Format, or layout, of the non-code part of a subprogram is called an activation record.
An activation record stores all the information about subprogram calls, activation records stores the following data (in the following order)
- Return address
- Static link – to the static parent (where the subprogram is declared).
- Dynamic link – to the caller of this subprogram.
- Parameters
- Local variables.
- Find the correct activation record instance
- Determine the correct offset within that activation record instance
A static chain is a chain of static links that connects certain activation record instances
Static_depth is an integer associated with a static scope representing the scope’s nesting depth
The chain_offset or nesting_depth of a non-local reference is the difference between the static_depth of the reference and that of the scope where it is declared
6. What are the two potential problems with the static chain methods?
- A nonlocal reference is slow if the number of scopes between the reference and the declaration of the referenced variable is large
- Time-critical code is difficult, because the costs of nonlocal references are not equal, and can change with code upgrades and fixes
One alternative to static chain is to use a display, for this approach, the static links are collected in a single array called a display. Display uses a pointer array to store the activation records along the static chain.
10. Explain the two methods of implementing block?
Blocks are treated as parameter less subprograms that are always called from the same place in the program.
Block can also be implemented in a different and somewhat simpler and more efficient way. The maximum amount of storage required for block variables at any time during the exaction of program can be statically determined, because block are entered and exited in strictly textual order.
11. Describe the deep access method of implementing dynamic scoping?
Deep Access – nonlocal references are found by searching the activation record instances on the dynamic chain. Length of chain cannot be statically determined every activation record instance must have variable names
12. Describe the shallow access method of implementing dynamic scoping?
In case of shallow access names and values are stored in a global table. Using this method, space is allocated for every variable name that is in the program (one space for variable temp though there might be several declarations of temp in the different methods). When a sub-routine is called it saves the current value of the variable and replaces it with the value in its current scope and restores the value of the variable while exiting.
14. Compare the efficiency of the deep access method to that of the shallow access method, in term of both call and nonlocal access?
The deep access methods provides fast subprogram linkage, but references to nonlocal, especially references to distant nonlocals (in term of the call chain), are costly. The shallow access methods provide much faster references to nonlocals, especially distant nonlocals, but are more costly in term of subprogram linkage.
Problem Set
7. It stated in this chapter that when nonlocal variables are accessed in a dynamic-scoped language using the dynamic chain, variable names must be stored in the activation records with the values. If this were actually done, every nonlocal access would require a sequence of costly string comparisons on names. Design an alternative to these string comparisons that would be faster.
One very simple alternative is to assign integer values to all variable names used in the program. Then the integer values could be used in the activation records, and the comparisons would be between integer values, which are much faster than string comparisons.
8. Pascal allows gotos with nonlocal targets. How could such statements be handled if static chains were used for nonlocal variable access?
Following the hint stated with the question, the target of every goto in a program could be represented as an address and a nesting_depth, where the nesting_depth is the difference between the nesting level of the procedure that contains the goto and that of the procedure containing the target. Then, when a goto is executed, the static chain is followed by the number of links indicated in the nesting_depth of the goto target. The stack top pointer is reset to the top of the activation record at the end of the chain.
9. The static-chain method could be expanded slightly by using two static links in each activation record instance where the second points to the static grandparent activation record instance. How would this approach affect the time required for subprogram linkage and nonlocal references?
Including two static links would reduce the access time to nonlocals that are defined in scopes two steps away to be equal to that for nonlocals that are one step away. Overall, because most nonlocal references are relatively close, this could significantly increase the execution efficiency of many programs.
11. If a compiler uses the static chain approach to implementing blocks, which of the entries in the activation records for subprograms are needed in the activation records for blocks?
There are two options for implementing blocks as parameterless subprograms: One way is to use the same activation record as a subprogram that has no parameters. This is the most simple way, because accesses to block variables will be exactly like accesses to local variables. Of course, the space for the static and dynamic links and the return address will be wasted. The alternative is to leave out the static and dynamic links and the return address, which saves space but makes accesses to block variables different from subprogram locals.
Concepts of Programming Languages Assignment - Chapter 9
Review Questions
1. What are the three general characteristics of subprograms?
• Each subprogram has a single entry point.
• The calling program unit is suspended during the execution of the called
subprogram, which implies that there is only one subprogram in execution
at any given time.
• Control always returns to the caller when the subprogram execution
terminates.
2. What does it mean for a subprogram to be active?
A subprogram is said to be active if, after having been called, it has begun execution but has not yet completed that execution.
3. What is given in a header of a subprogram?
A subprogram header, which is the first part of the definition, serves several purposes. First, it specifies that the following syntactic unit is a subprogram definition of some particular kind.1 In languages that have more than one kind of subprogram, the kind of the subprogram is usually specified with a special word. Second, if the subprogram is not anonymous, the header provides a name for the subprogram. Third, it may optionally specify a list of parameters.
4. What characteristic of Python subprograms sets them apart from those of other languages?
One characteristic of Python functions that sets them apart from the functions of other common programming languages is that function def statements are executable. When a def statement is executed, it assigns the given name to the given function body. Until a function’s def has been executed, the function cannot be called. Consider the following skeletal example:
if . . .
def fun(. . .):
. . .
else
def fun(. . .):
. . .
5. What languages allow a variable number of parameters?
C# allows methods to accept a variable number of parameters, as long as they are of the same type.
6. What is a Ruby array formal parameter?
Ruby supports a complicated but highly flexible actual parameter configuration. The initial parameters are expressions, whose value objects are passed to the corresponding formal parameters. The initial parameters can be following by a list of key => value pairs, which are placed in an anonymous hash and a reference to that hash is passed to the next formal parameter. These are used as a substitute for keyword parameters, which Ruby does not support. The hash item can be followed by a single parameter preceded by an asterisk. This parameter is called the array formal parameter.
23. What is Automatic Generalization?
The type inferencing system of F# is not always able to determine the type of parameters or the return type of a function. When this is the case, for some functions, F# infers a generic type for the parameters and the return value. This is called automatic generalization.
24. What is an overloaded subprogram?
An overloaded subprogram is a subprogram that has the same name as another subprogram in the same referencing environment.
25. What is ad hoc binding?
Ad hoc binding is when the environment of the call statement that passed the subprogram as an actual parameter.
26. What is multicast delegate?
All of the methods stored in a delegate instance are called in the order in which they were placed in the instance. This is called a multicast delegate.
30. What are the design issues for functions?
The following design issues are specific to functions:
• Are side effects allowed?
• What types of values can be returned?
• How many values can be returned?
31. What two languages allow multiple values to be returned from a function?
Ruby allows the return of more than one value from a method. Lua also allows functions to return multiple values.
Problem Set
3. Argue in support of the template functions of C++. How is it different from the template functions in other languages?
C++ templated classes are instantiated to become typed classes at compile time. For example, an instance of the templated Stack class, as well as an instance of the typed class, can be created with the following declaration:
Stack<int> myIntStack;
However, if an instance of the templated Stack class has already been created for the int type, the typed class need not be created.
6 . Compare and contrast PHP’s parameter passing with that of C#.
PHP’s parameter passing is similar to that of C#, except that either the actual parameter or the formal parameter can specify pass-by-reference. Passby- reference is specified by preceding one or both of the parameters with an ampersand.
8 . Argue against the Java design of not providing operator overloading
Arithmetic operators are often used for more than one purpose. For example, + usually is used to specify integer addition and floating-point addition. Some languages—Java, for example—also use it for string catenation. This multiple use of an operator is called operator overloading and is generally thought to be acceptable, as long as neither readability nor reliability suffers.
12 . Research Jensen’s Device, which was a widely known use of pass-by-name parameters, and write a short description of what it is and how it can be used.
Implementing a pass-by-name parameter requires a subprogram to be passed to the called subprogram to evaluate the address or value of the formal parameter. The referencing environment of the passed subprogram must also be passed. This subprogram/referencing environment is a closure. Pass-by-name parameters are both complex to implement and inefficient. They also add significant complexity to the program, thereby lowering its readability and reliability. Because pass-by-name is not part of any widely used language, it is not discussed further here. However, it is used at compile time by the macros in assembly languages and for the generic parameters of the generic subprograms in C++, Java 5.0, and C# 2005.
15. How is the problem of passing multidimensional arrays handles by Ada?
Ada compilers are able to determine the defined size of the dimensions of all arrays that are used as parameters at the time subprograms are compiled. In Ada, unconstrained array types can be formal parameters. An unconstrained array type is one in which the index ranges are not given in the array type definition. Definitions of variables of unconstrained array types must include index ranges. The code in a subprogram that is passed an unconstrained array can obtain the index range information of the actual parameter associated with such parameters
1. What are the three general characteristics of subprograms?
• Each subprogram has a single entry point.
• The calling program unit is suspended during the execution of the called
subprogram, which implies that there is only one subprogram in execution
at any given time.
• Control always returns to the caller when the subprogram execution
terminates.
2. What does it mean for a subprogram to be active?
A subprogram is said to be active if, after having been called, it has begun execution but has not yet completed that execution.
3. What is given in a header of a subprogram?
A subprogram header, which is the first part of the definition, serves several purposes. First, it specifies that the following syntactic unit is a subprogram definition of some particular kind.1 In languages that have more than one kind of subprogram, the kind of the subprogram is usually specified with a special word. Second, if the subprogram is not anonymous, the header provides a name for the subprogram. Third, it may optionally specify a list of parameters.
4. What characteristic of Python subprograms sets them apart from those of other languages?
One characteristic of Python functions that sets them apart from the functions of other common programming languages is that function def statements are executable. When a def statement is executed, it assigns the given name to the given function body. Until a function’s def has been executed, the function cannot be called. Consider the following skeletal example:
if . . .
def fun(. . .):
. . .
else
def fun(. . .):
. . .
5. What languages allow a variable number of parameters?
C# allows methods to accept a variable number of parameters, as long as they are of the same type.
6. What is a Ruby array formal parameter?
Ruby supports a complicated but highly flexible actual parameter configuration. The initial parameters are expressions, whose value objects are passed to the corresponding formal parameters. The initial parameters can be following by a list of key => value pairs, which are placed in an anonymous hash and a reference to that hash is passed to the next formal parameter. These are used as a substitute for keyword parameters, which Ruby does not support. The hash item can be followed by a single parameter preceded by an asterisk. This parameter is called the array formal parameter.
23. What is Automatic Generalization?
The type inferencing system of F# is not always able to determine the type of parameters or the return type of a function. When this is the case, for some functions, F# infers a generic type for the parameters and the return value. This is called automatic generalization.
24. What is an overloaded subprogram?
An overloaded subprogram is a subprogram that has the same name as another subprogram in the same referencing environment.
25. What is ad hoc binding?
Ad hoc binding is when the environment of the call statement that passed the subprogram as an actual parameter.
26. What is multicast delegate?
All of the methods stored in a delegate instance are called in the order in which they were placed in the instance. This is called a multicast delegate.
30. What are the design issues for functions?
The following design issues are specific to functions:
• Are side effects allowed?
• What types of values can be returned?
• How many values can be returned?
31. What two languages allow multiple values to be returned from a function?
Ruby allows the return of more than one value from a method. Lua also allows functions to return multiple values.
Problem Set
3. Argue in support of the template functions of C++. How is it different from the template functions in other languages?
C++ templated classes are instantiated to become typed classes at compile time. For example, an instance of the templated Stack class, as well as an instance of the typed class, can be created with the following declaration:
Stack<int> myIntStack;
However, if an instance of the templated Stack class has already been created for the int type, the typed class need not be created.
6 . Compare and contrast PHP’s parameter passing with that of C#.
PHP’s parameter passing is similar to that of C#, except that either the actual parameter or the formal parameter can specify pass-by-reference. Passby- reference is specified by preceding one or both of the parameters with an ampersand.
8 . Argue against the Java design of not providing operator overloading
Arithmetic operators are often used for more than one purpose. For example, + usually is used to specify integer addition and floating-point addition. Some languages—Java, for example—also use it for string catenation. This multiple use of an operator is called operator overloading and is generally thought to be acceptable, as long as neither readability nor reliability suffers.
12 . Research Jensen’s Device, which was a widely known use of pass-by-name parameters, and write a short description of what it is and how it can be used.
Implementing a pass-by-name parameter requires a subprogram to be passed to the called subprogram to evaluate the address or value of the formal parameter. The referencing environment of the passed subprogram must also be passed. This subprogram/referencing environment is a closure. Pass-by-name parameters are both complex to implement and inefficient. They also add significant complexity to the program, thereby lowering its readability and reliability. Because pass-by-name is not part of any widely used language, it is not discussed further here. However, it is used at compile time by the macros in assembly languages and for the generic parameters of the generic subprograms in C++, Java 5.0, and C# 2005.
15. How is the problem of passing multidimensional arrays handles by Ada?
Ada compilers are able to determine the defined size of the dimensions of all arrays that are used as parameters at the time subprograms are compiled. In Ada, unconstrained array types can be formal parameters. An unconstrained array type is one in which the index ranges are not given in the array type definition. Definitions of variables of unconstrained array types must include index ranges. The code in a subprogram that is passed an unconstrained array can obtain the index range information of the actual parameter associated with such parameters
Langganan:
Postingan (Atom)