Concept of Programming Language: Chapter 15

Lecturer: Mr. Tri Djoko Wahjono, Ir, M.Sc.

 

Review Question

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

Advertisements

Concept of Programming Language: Chapter 14

Lecturer: Mr. Tri Djoko Wahjono, Ir, M.Sc.

 

Review Question

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 subprogramexecution 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 inJava?

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.

Concept of Programming Language: Chapter 13

Lecturer: Mr. Tri Djoko Wahjono, Ir, M.Sc.

 

Review Question

1. What are the three possible levels of concurrency in programs?

– 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)

7. What is the difference between physical and logical concurrency?

Physical concurrency is several program units from the same program that literally execute simultaneously.
Logical concurrency is multiple processors providing actual concurrency, when in fact the actual execution of programs is taking place in interleaved fashion on a single processor.

8. What is the work of a scheduler?

Scheduler manages the sharing of processors among the tasks.

12. What is a heavyweight task? What is a lightweight task?

Heavyweight task executes in its own address space. Lightweight task all run in the same address space.

16. What is a task descriptor?

Task descriptor is a data structure that stores all of the relevant information about the execution state of a task.

18. What is the purpose of a task-ready queue?

The purpose of a task-ready queue is to be storage of tasks that are ready to run.


21. What is a binary semaphore? What is a counting semaphore?

Binary semaphore is a semaphore that requires only a binary-valued counter, like the one used to provide competition synchronization. A counting semaphore is a synchronization object that can have an arbitrarily large number of states.

30. What is purpose of an Ada terminate clause?

The purpose of an Ada terminate clause is to mark that the task is finished with its job but is not yet terminated.

34. What does the Java sleep method do?

Sleep method blocks the the thread.

35. What does the Java yield method do?

Yield method surrenders the processor voluntarily as a request from the running thread.

36. What does the Java join method do?

Java forces a method to delay its execution until the run method of another thread has completed its execution.

37. What does the Java interrupt method do?

Interrupt becomes one way to communicate to a thread that it should stop.

55. What is Concurrent ML?

Concurrent ML is an extension to ML that includes a fform of threads and a form of synchronous message passing to support concurrency.

56. What is the use of the spawn primitive of CML?

The use of Spawn primitive of CML is to create a thread.

57. What is the use of subprograms BeginInvoke and EndInvoke in F#?

The use of subprograms BeginInvoke and Endinvoke in F# is to call threads asynchronously.

58. What is the use of the DISTRIBUTE and ALIGN specification of HPC?

The use of DISTRIBUTE and ALIGN specification of HPC is to provide information to the compiler on machines that do not share memory, that is, each processor has its own memory.

Problem Set

1. Explain clearly why a race condition can create problems for a system.

Because 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). The importance of competition synchronization should now be clear.

2. What are the different ways to handle deadlock?

– Ignoring deadlock
– Detection
– Prevention
– Avoidance

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?

Busy-waiting or spinning is a technique in which a process repeatedly checks to see if a condition is true, such as whether keyboard input or a lock is available.
Spinning can also be used to generate an arbitrary time delay, a technique that was necessary on systems that lacked a method of waiting a specific length of time.
Processor speeds vary greatly from computer to computer, especially as some processors are designed to dynamically adjust speed based on external factors, such as the load on the operating system.
Busy waiting may loop forever and it may cause a computer freezing.

Concept of Programming Language: Chapter 12

Lecturer: Mr. Tri Djoko Wahjono, Ir, M.Sc.

Review Question

2. What are the problems associated with programming using abstract data types?

-In nearly all cases, the features and capabilities of the existing type are not quite right for the new use.

-The type definitions are all independent and are at the same level.

 

5. What is an overriding method?

Overriding method is method that overrides the inherited method.

 

6. Describe a situation where dynamic binding is a great advantage over its absence.

Consider the following situation: There is a base class, A, that defines a method draw that draws some figure associated with the base class. A second class, B, is defined as a subclass of A. Objects of this new class also need a draw method that is like that provided by A but a bit different because the subclass objects are slightly different. So, the subclass overrides the inherited draw method. If a client of A and B has a variable that is a reference to class A’s objects, that reference also could point at class B’s objects, making it a polymorphic reference. If the method draw, which is defined in both classes, is called through the polymorphic reference, the run-time system must determine, during execution, which method should be called, A’s or B’s.

 

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.

 

25. What is mixins in objective-C?

Mixins are sometimes used to add certain functionalities to different classes. And, of course, the class still has a normal superclass from which it inherits members. So, mixins 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.

 

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.

 

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.

13. Descripbe the mechanism of dynamic dispatch with an example in Java. Is it possible to dynamically dispatch the data members?

In C++, a method must be defined as virtual to allow dynamic binding. In Java, all method calls are dynamically bound unless the called method has been defined as final, in which case it cannot be overridden and all bindings are static. Static binding is also used if the method is static or private, both of which disallow overriding.

16. State why java is said to be more pure object-oriented than C++.

Java’s design for supporting object-oriented programming is similar to that of C++, but it employs more consistent adherence to object-oriented principles. Java does not allow parentless classes and uses dynamic binding as the “normal” way to bind method calls to method definitions. This, of course, increases execution time slightly over languages in which many method bindings are static. At the time this design decision was made, however, most Java programs were interpreted, so interpretation time made the extra binding time insignificant. Access control for the contents of a class definition are rather simple when compared with the jungle of access controls of C++, ranging from derivation controls to friend functions. Finally, Java uses interfaces to provide a form of support for multiple inheritance, which does not have all of the drawbacks of actual multiple inheritance.

 

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.

Concept of Programming Language: Chapter 11

Lecturer: Mr. Tri Djoko Wahjono, Ir, M.Sc.

Review Question

1. What are the two kinds of abstraction in programming language?

Two kinds of abstractions in programming languages are process abstraction and data abstraction.
2. Define abstract data type.

abstract data type (ADT) is a mathematical model for a certain class of data structures that have similar behavior; or for certain data types of one or more programming languages that have similar semantics
3. What are the advantages of the two parts of the definition of abstract data type

Program organization, modifiability (everything associated with a data structure is together), and separate compilation.
The representation of objects of the type is hidden from the program units that use these objects, so the only operations possible are those provided in the type’s definition

5. What are the language design issues for abstract data type?

There are three language design issues. First, the form of the container for the interface to the type. Second, is whether the abstract data type can be parameterized or not. And last, is what access controls are provided and how such controls are specified.

6. Explain how information hiding is provided in an Ada package.

– The representation of type appears in a part of the specification called the private part
– More restricted form with limited private types
– Define the ADT as a pointer and provide the pointed to structure’s definition in the body package

7. . To what is the private part of an Ada package specification visible?

The private clause is visible to the compiler but not to the client program units.

8. What is the difference between private and limited private types in Ada

Private is to represent the type appears in a part of the specification. The difference from limited private is that object of a type that is declared limited private has no built-in operations. Limited private type is useful when the usual predefined operation of assignments and comparison are not meaningful  of useful

9. What is in an Ada package specification? What about the body package

Ada’s package specification provides the interface of the encapsulation, and the body package provides the implementation of most, if not all, of the entities named in the associated package specification. The body package must have subprograms that match the headings in the associated package specification

10. What is the use of the Ada with clause?

The with clause makes the names defined in external package visible

11. What is the use of the Ada use clause?
The use clause eliminates the need for explicit qualification of the references to entities from the named package

12. What is the fundamental difference between C++ class and an Ada package

The difference between C++ class and Ada package is that Ada packages are more generalized encapsulation than can define any number of types.

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.

9. What happens if the constructor is absent in Java and C++?

It will be made automatically by the built-up in.

10. Which two conditions make data type “abstract” ?

– The representation, or definition, of the type and the operations are contained in a single syntactic unit
– The representation of objects of the type is hidden from the program units that use the type, so only direct operations possible on those objects are those provided in the type’s definition

17. The namespace of the C# standard library, System, is not implicitly available to C# programs. Do you think this is a good idea? Defend your answer.

I think it is not, because it reduces its efficiency.

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.*

Concept of Programming Language: Chapter 10

Lecturer: Mr. Tri Djoko Wahjono, Ir, M.Sc.

Review Question

4. What is the task of a linker?

Task of a linker is to find the files that contain the translated subprograms referenced in that program and load them into memory.  Then , the linker must set the target addresses of all calls to those subprograms in the main program to the entry addresses of those subprograms.

 

5. What are the two reasons why implementing subprograms with stack-dynamic local variables is more difficult than implementing simple subprograms?

-The compiler must generate code to cause the implicit allocation and deallocation of local variables.

-Recursion adds the possibility of multiple simultaneous activations of a subprogram, which means that there can be more than one instance (incomplete execution) of a subprogram at a given time, with at least one call from outside the subprogram and one or more recursive calls. The number of activations is limited only by the memory size of the machine. Each activation requires its activation record instance.

 

15. Explain the two methods of implementing blocks.

– Blocks can be implemented by using the static-chain process for implementing nested subprograms. Blocks are treated as parameterless subprograms that are always called from the same place in the program. Therefore, every block has an activation record. An instance of its activation record is created every time the block is executed.

– Blocks 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 execution of a program can be statically determined, because blocks are entered and exited in strictly textual order. This amount of space can be allocated after the local variables in the activation record. Offsets for all block variables can be statically computed, so block variables can addressed exactly as if they were local variables.

 

16. Describe the deep-access method of implementing dynamic scoping.

The dynamic chain links together all subprogram activation records instances in the reverse of the order in which they were activated. Therefore, the dynamic chain is exactly what is needed to reference non-local variables in a dynamic-scoped language.

 

17. Describe the shallow-access method of implementing dynamic scoping.

Shallow access is an alternative implementation method, not an alternative semantics. The semantics of deep access and shallow access are identical. In the shallow-access method, variables declared in subprograms are not stored in the activation records of those subprograms.

 


Problem Set

 8. Pascal allows gotos with nonlocal targets. How could such statements be handled if static chains were used for non-local variable access?

Finding the correct activation record instance of a nonlocal variable using static links is relatively straightforward. When a reference is made to nonlocal variable, the activation record instance containing the variable can be found by searching the static chain until a static ancestor activation record instance is found that contains the variable.

 

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?

The nesting of scopes is known at compile time, the compiler can determine not only that a reference is nonlocal but also the length of the static chain that must be followed to reach the activation records instance that contains the nonlocal object.

 

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?

A static chain is a chain of static links that connect certain activation record instances in the stack. During the execution of a subprogram P, the static link of its activation record instance points to an activation record instance of P’s static parent program unit. That instance’s static link points in turn to P’s static grandparent program unit’s activation record instance, if there is one. So, the static chain connects all the static ancestors of an executing subprogram, in order of static parent first. This chain can obviously be used to implement the accesses to nonlocal variables in static-scoped languages.

Concept of Programming Language: Chapter 9

Lecturer: Mr. Tri Djoko Wahjono, Ir, M.Sc.

Review Questions

1. What are the three general characteristics of subprograms?
Each subprogram has a single entry point, excluding co-routine.
The calling program 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.
4. What are formal parameters? What are actual parameters?
The parameters in the subprogram header are called formal parameters.
Subprogram call statements must include the name of the subprogram and alist of parameters to be bound to the formal parameters of the subprogram. These parameters are called actual parameters.
5. What are the advantages and disadvantages of keyword parameters?
The advantage of keyword parameter is that they can appear in any order in the actual parameter list.
The disadvantage to keyword parameters is that the user of the subprogram must know the names of formal parameters.
6. What are the design issues for subprograms?
What parameter-passing method or methods are used?
Are the types of the actual parameters checked against the types of the formal parameters?
Are local variable statically or dynamically allocated?
Can subprogram definitions appear in other subprogram definitions?
If subprograms can be passed as parameters and subprograms can be nested, what is the referencing environment of a passed subprogram?
Can a subprogram be overloaded?
Can subprograms be generic?
7. What are the advantages and disadvantages of dynamic local variables?
Advantages:
They provide flexibility to the subprogram
The storage of local variables in an active subprogram can be shared with the local variables in all inactive subprograms.
They efficiently used when computer has small memory (Faster Access).
Disadvantages:
Cost of the time required to allocate
Access to dynamic local variable must be indirect
The stack dynamic local variables, subprograms cannot be history sensitive
9. What are the modes, the conceptual modes of transfer, the advantages, and the disadvantages or pass-by-value, pass-by-result, pass-by-value-result, and pass-by-reference parameter-passing models?
There are two conceptual models of how data transfers take place in parameter transmission. Either an actual value is copied or an access path is transmitted.
The advantage of pass-by-value is its speed.
The disadvantages of pass-by-value are, when copies are used, additional storage is required.
Storage and copy operations can be costly.
Pass-by-result has all of the advantages and disadvantages of pass-by-value, but more disadvantages. An additional disadvantage is that there can be an actual parameter collision, because order of expressions matter.
Pass-by-value-result has the same advantages and disadvantages as pass-by-value and pass-by-result with some more advantages. The largest extra advantage of pass-by-value-result is that it solves pass-by-reference’s aliasing problems.
An advantage of pass-by-reference is that it is efficient in both time and space.
A disadvantage to pass-by-reference is the increase in time to access formal parameters because of the additional level of indirect addressing. Secondly, if only one way communication to the called subprogram is required, inadvertent and erroneous changes may be made to the actual parameter. Finally, aliasing should be expected with pass-by-reference. Since pass-by-reference makes access paths available to the called subprograms, it broadens their access to nonlocal variables. These aliasing problems lead to decreased readability and reliability.
10. In what ways can aliases occur with pass-by-reference parameters?
Aliases can be occurring because pass-by-reference makes access paths available to the called subprograms.
17. What is parametric polymorphism?
Parametric polymorphism is provided by a subprogram that takes a generic parameter that is used in a type expression that describes the types of the parameters of the subprogram. Both Ada and C++ provides a kind of compile-time parametric polymorphism.
18. What causes a C++ template function to be instantiated?
C++ template functions are instantiated implicitly either when the function is named in a call or when its address is taken with the & processor.
19. In what fundamental way do the generic parameters to a Java 5.0 generic method differ from those of C++ methods?
Java does not use objects exclusively, java have no enumeration or record type. Whereas C++ Classes can be defined to have no parent, that is not possible in Java. All Java Classes must be subclass of the root class.
20. If a Java 5.0 method returns a generic type, what type of object is actually returned?
In Java any type or class can be returned by methods. Because methods are not types, they cannot be returned.
22. What are the design issues for functions?
Two design issues are functions.
Are side effects allowed?
What types of values can be returned?
23. In what ways are coroutines different from conventional subprogram?
Conventional subprograms are subordinate to their callers. When a routine calls a subprogram, execution suspends at that point in the program and resumes after the subprogram has run to completion. As a result, conventional subprogram invocation is atomic, much like a built-in statement in the programming language.
Problem Set
4. Suppose you want to write a method that prints a heading on a new output page,  along with a page number that is 1 in the first activation and that increases by 1 with each subsequent activation. Can this be done without parameters and without reference to nonlocal variables in Java? Can it be done in C#?
This can be done in both Java and C#, using a static (or class) data member for the page number.
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. Pass-by reference is specified by preceding one or both of the parameters with an ampersand.
7. Consider the following program written in C syntax:
void fun (int first, int second){
 
 first += first;
 
 second += second;
 
}
 
void main() {
 
 int list [2] = {3,5};
 
 fun(list[0], list[1]);
 
}
For each of the following parameter-passing methods, what are the values of the list array after execution?
a. Passes by value
b. Passes by reference.
c. Passes by value-result
a. 3, 5
b. 6, 10
c. 6, 10
11. Compare the use of closures by programming languages.
Nearly all functional programming languages, most scripting languages, and at least one primarily imperative language, C#, support closures. These languages are static-scoped, allow nested subprograms, and allow subprograms to be passed as parameters.
15. How is the problem of passing multidimensional arrays handled 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.