Friday 28 June 2013

Chapter 16 of Concept of Programming Languages

Review Questions : 

2.What are the two parts of a compound term?
A compound term is composed of two parts, a functor and an ordered list of parameter

5. What are the antecedents? Consequent?
 The right side of a clausal form proposition is called the antecendent. The left side is called the consequent because it is the consequence of the truth antecendent

7. What are the forms of Horn clauses?
 Horn clauses can be in only two forms: they have either a single atomic proposition on the left side or an empty left side.

8. What is the basis concept of declarative semantics?
 The basic concept of this semantics is that there is a simple way to determine the meaning of each statement, and it does not depend on how the statement might be used to solve a problem

10. What are the three forms of a Prolog term?
 A prolog term is a constant, a variable, or a structure

11. What is an uninstantiated variable?
 A variable that has not been assigned a value is called uninstantiated
 
Problem Set :


1. ”All predicate calculus propositions can be algorithmically converted to clausal form”. Is this 
statement true or false? Explain
 The statement is true. this was proven by Nilsson (1971) by using a simple conversion algorithm

2. Describe how a logic programming language is different from a general programming language
  Logical programming language uses a form of symbolic logic, the syntax of logic programming logic is remarkably different from that of the imperative and functional languages.

Chapter 15 of Concept of Programming Languages

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


2 . Give a general form of function declaration in ML.
Function declarations in ML appear in the general form
fun function_name(formal parameters) = expression;


4. Refer to a book on Haskell programming and discuss the features of Haskell.
Haskell features lazy evaluation, pattern matching, list comprehension, type classes, and type polymorphism.


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.


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-NIL atoms in the given list.

Chapter 14 of Concept of Programming Languages

Review Question

6 . What is exception propagation in Ada?
Exception propagation allows an exception raised in one program unit to be handled in some other unit in its dynamic or static ancestry. This allows a single exception handler to be used for any number of different program units. This reuse can result in significant savings in development cost, program size, and program complexity.


9. What is the scope of exception handlers in Ada?
Exception handlers can be included in blocks or in the bodies of subprograms, packages, or tasks.


10. What are the four exceptions defined in the Standard package of Ada?
There are four exceptions that are defined in the default package, Standard:

Constraint_aError  
Program_Error 
Storage_Error 
Tasking_Error


11. are they any predefined exceptions in Ada?
Yes, they are.


12. What is the use of Suppress pragma in Ada?
The suppress pragma is used to disable certain run-time checks that
are parts of the built-in exceptions in Ada.


14. What is the name of all C++ exception handlers?
Try clause.


15. Which standard libraries define and throw the exception out_of_rangein C++?
Library container classes.


16. Which standard libraries define and throw the exception overflow_errorin C++?
Math library functions.


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


30. In which version were assertions added to Java?
Assertions were added to Java in version 1.4.


31. What is the use of the assert statement?
The assert statement is used for defensive programming. A program may be written with many assert statements, which ensure that the program’s computation is on track to produce correct results.


32. What is event-driven programming?
Event-driven programming is a programming where parts of the program are executed at completely unpredictable times, often triggered by user interactions with the executing program.


33. What is the purpose of a Java JFrame?
The JFrame class defines the data and methods that are needed for frames. So, a class that uses a frame can be a subclass of JFrame. A JFrame has several layers, called panes.


34. What are the different forms of assert statement?
There are two possible forms of the assert statement:
assert condition;
assert condition : expression;



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.

Chapter 13 of Concept of Programming Languages

Review Questions : 

7. What is the difference between physical and logical concurrency?
 Several program units from the same program executes simultaneously, this is called physical concurrency, while logical concurrency the actual execution of program is taking place in interlaved fashion on a single processor

8. What is the work of a scheduler?
 A scheduler manages the sharing of processors among the tasks.

9. Give some examples of languages which can be used for synchronization
 Ada, Java, C#, F#, Python

10. When a task in a blocked state?
 A task that is blocked has been running, but that execution was interrupted by one of several different events, the most common of which is an input or output operation.

18. What is the purpose of a task-ready queue?
  a ready task is ready to run but is not currently running, either it has not been given processor time by the scheduler, or it had run previously but was blocked

19. What are the two primary design issues for language support for concurrency?
 Competition and cooperation synchronization

20. Describe the actions of the wait and release operations for semaphores
 The wait semaphore subprogram is used to test the counter of a given semaphore variable. The release semaphore subprogram is used by a task to allow some other task to have one of whatever the counter of the specified semaphore variable counts

34. What does the Java sleep method do?
 Sleep method specify the number of milliseconds the thread want to be blocked and block the thread for that amount of milliseconds

35. What does the Java yield method do?
 Join method is used to force a method to delay its execution until the run method of another thread has completed its execution

36. What does the Java join method do?
  The join method puts the thread that calls it in the blocked state, which can be ended only by the completion of the thread on which join was called.

37. What does the Java interrupt method do?
 The interrupt method is one way to communicate to a thread that it should stop

48. What kind of methods can run in a C# threads?
 Any C# method can run in its own thread

49. Can C# threads be actor threads, server threads, or either?
 C# support both actor and server threads.

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

56. What is the use of spawn primitive of CML?
 Creating a thread in CML

____________________________________________________________________________________________________________________________________

Problem Set  :


2. What are the different ways to handle deadlock?
 Deadlock handling :
  • Ignoring deadlock
  • Detection : Process Terimnation and Resource preemption
  • Prevention : preventing one of the four Coffman conitions from occuring
  • 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?
The main problem would be the CPU resources that area allocated to the waiting for the task, if it were to be suspended, the CPU can then be used for other purposes

Chapter 12 of Concept of Programming Languages

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.
4. What is message protocol?
The entire collection of methods of an object is called the message protocol, or message interface, of the object.

5. What is an overriding method?
An overriding method is a method that provide an operation in the subclass that is similar to one in the parent class, but is customized for objects of the subclass. For example, a parent class, Bird, might have a draw method that draws a generic bird. A subclass of Bird named Waterfowl could override the draw method inherited from Bird to draw a generic waterfowl, perhaps a duck.

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.

8. What is an abstract method? What is an abstract class?
For example, suppose a program defined a Building class and a collection of subclasses for specific types of buildings, for instance, French_Gothic. It probably would not make sense to have an implemented draw method in Building. But because all of its descendant classes should have such an implemented method, the protocol (but not the body) of that method is included in Building. Such a method is often called an abstract method ( pure virtual method in C++). A class that includes at least one abstract method is called an abstract class (abstract base class in C++).

10. What is an inner class?
Inner classes are non-static classes that are nested directly in another class.

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


1 . What important part of support for inheritance is missing in Java?
Java does not support the private and protected derivations of C++. One can surmise that the Java designers believed that subclasses should be subtypes, which they are not when private and protected derivations are supported. Thus, they did not include them.


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.
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 is greatly facilitated without requiring changes 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 relationships 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?
Finalize is related to C++ destructor. A finalize method is implicitly called when the garbage collector is about to reclaim the storage occupied by the object. The problem with finalize is that the time it will run cannot be forced or even predicted. The alternative to using finalize to reclaim resources held by an object about to be garbage collected is to include a method that does the reclamation. The only problem with this is that all clients of the objects must be aware of this method and remember to call it.


20. Compare the way Smalltalk provides dynamic binding with that of C++.
In C++, the programmer can specify whether static binding or dynamic binding is to be used. Because static binding is faster, this is an advantage for those situations where dynamic binding is not necessary. Furthermore, even the dynamic binding in C++ is fast when compared with that of Smalltalk. Binding a virtual member function call in C++ to a function definition has a fixed cost, regardless of how distant in the inheritance hierarchy the definition appears. Calls to virtual functions require only five more memory references than statically bound calls (Stroustrup, 1988). In Smalltalk, however, messages are always dynamically bound to methods, and the farther away in the inheritance hierarchy the correct method is, the longer it takes. The disadvantage of allowing the user to decide which bindings are static and which are dynamic is that the original design must include these decisions, which may have to be changed later.


21. Compare the support for polymorphism in C# with that of in Objective-C.
In Objective-C, polymorphism is implemented in a way that differs from the way it is done in most other common programming languages. A polymorphic variable is created by declaring it to be of type id. Such a variable can reference any object. The run-time system keeps track of the class of the object to which
an id type variable refers. If a call to a method is made through such a variable, the call is dynamically bound to the correct method, assuming one exists.
To allow dynamic binding of method calls to methods in C#, both the base method and its corresponding methods in derived classes must be specially marked. The base class method must be marked with virtual, as in C++. To make clear the intent of a method in a subclass that has the same name and protocol as a virtual method in an ancestor class, C# requires that such methods be marked override if they are to override the parent class virtual method.


25. Study and explain private and public modifiers in C++. How do those modifiers differ in C#?
C++ includes both classes and structs, which are nearly identical constructs. The only difference is that the default access modifier for class is private, whereas for structs it is public. C# also has structs, but they are very different from those of C++. In C#, structs are, in a sense, lightweight classes. They can have constructors, properties, methods, and data fields and can implement interfaces but do not support inheritance.

Chapter 11 of Concept of Programming Languages

Review Questions : 

1. What are the two kinds of abstractions in programming languages?
 process abstraction and data abstraction

2. Define ADT
 ADT is a data type that is hidden from the program units, and the declaration of the type and the protocols, are contained in a single syntactic unit

3. What are the advantages of the two parts of the definition of abstract data type?
 Information hiding, improved readability, and easier to manage

5. What are the language design issues for ADT?
 Form of the container for the interface to the type, whether ADT can be parameterized,  type of access controls, whether the specification of the type is separate from its implementation

6. Explain how information hiding is provided in an Ada package
 In Ada, the designer of an Ada package can choose to make the type entirely visible to clients or provide only the interface information.

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?
 Limited private type is a more restricted form of private types

10. What is the use of the Ada with clause?
 The with clause makes the names defined in external packages visible

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

12. What is the fundamental difference between a C++ Class and and Ada package?
 C++ classes are types, Ada packages are more generalized encapsulations that can define any number of types. A c++ program unit that declares an instance of a class can access any of the public entities in that class, but only through an instance of the class instead of Ada package, in which a program unit that gains visibility can access public entities by their names

13. From where are C++ object allocated?
In the function where an object is created


14. In what different places can the definition of a C++ member function appear?
 In the class or only in its header

__________________________________________________________________________________________________________________________________________________________________________________
Problem Set Questions :


3. Write an analysis of the similarities of and differences between the access specifier of Java and C++
 Answer :

C++ and Java use classes, however in Java, reliability gets prioritized over flexibility, Java and C++ classes are very similar in the term of using protected, public, and private. Each access specifier is the same whether in C++ or Java, in C++ private can only be accessed inside the class, protected is private but can be inherited to a child class, and public is accessible from outside the class. Java however need to specify everything in when we declare a variable, while in C+ we only need to write protected or private only once. Method must be defined inside of a class in Java, and all objects are allocated form the heap and accessed through reference variables.



4. What are the advantages of the nonpointer concept in Java?
 The nonpointer concept in Java basically means that pointer is no longer included in Java. Pointer is a powerful but dangerous tool to use, A dangling pointer can have an impact to the overall program reliability, hence why java decided not to include pointers. The advantages is that java program is basically more reliable, and not prone to error without the existence of pointers.

9. What happens if the constructors are absent in Java and C++?
 We cannot assign values that we want on the creation time of the object, instead we have to make a separate function to assign values, and this can take time.

11. Why is the destructor of C# is rarely used?
 Because C# uses garbage collection for most of its heap objects.

15. Give one capability that Java 5.0 provides which C# 2005 does not.
Answer :
One capability that Java 5.0 provides that C# 2005 does not is wildcard classes 

Chapter 10 of Concept of Programming Languages

Review Question

1. What is the definition used in this chapter for “simple” subprograms?
By “simple” they mean that subprograms cannot be nested and all local variables are static.


2. Which of the caller or callee saves execution status information?
The last three actions of a call clearly must be done by the caller. Saving the execution status of the caller could be done by either.


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.

11 . What is an EP, and what is it’s purpose?
EP is required to control the execution of a subprogram. Initially, the EP points at the base, or first address of the activation record instance of the main program. Therefore, the run-time system must
ensure that it always points at the base of the activation record instance of the currently executing program unit. When a subprogram is called, the current EP is saved in the new activation record instance as the dynamic link. The EP is then set to point at the base of the new activation record instance. Upon return from the subprogram, the stack top is set to the value of the current EP minus one and the EP is set to the dynamic link from the activation record instance of the subprogram that has completed its execution. Resetting the stack top effectively removes the top activation record instance.



16 . Describe the deep-access method of implementing dynamic scoping.
If local variables are stack dynamic and are part of the activation records in a
dynamic-scoped language, references to nonlocal variables can be resolved by searching through the activation record instances of the other subprograms that are currently active, beginning with the one most recently activated. This concept is similar to that of accessing nonlocal variables in a static-scoped language with nested subprograms, except that the dynamic—rather than the static—chain is followed. The dynamic chain links together all subprogram activation record instances in the reverse of the order in which they were activated. Therefore, the dynamic chain is exactly what is needed to reference nonlocal variables in a dynamic-scoped language. This method is called deep access, because access may require searches deep into the stack.




Problem Set


7. It is 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?
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.

Chapter 9 of Concept of Programming Languanges

Review Questions : 
1. What are the three general characteristics of subprograms?
 Characteristics :
  • Each subprogram has a single entry point
  • The calling program unit is suspended during the execution of the called subprgoram, which implies thtat 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?
  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 the header of a subprogram?
 The definition, a name, and a specification of parameters

4. What characteristic of Python subprograms sets them apart from those of other language?
 The function def statementes are executable, when def statements are executed, the functions cannot be called.

5. What languages allow a variable number of parameters?
 C# allows methods to accept a variable number of parameters, as long as they are the of the same type.

11. What are design issues for subprograms?
 Design issues :
  • Are the local variables statically or dynamically allocated?
  • Can subprogram definitions appear in other subprogram definitions?
  • What parameter passing method are used?
  • Are the type of the actual parameter checked against the type of the formal parameters?
  • Can subprogram be overloaded?
  • Can subprogram be generic?
  • If the language allows nested subprograms, are closure supported ?

12. What are the advantages and disadvantages of dynamic local variable?
 The Advantages :
  • Dynamic local variable is slightly more efficient
  • They require no run time overhead for allocation or deallocation
  • They allow subprograms to be history sensitive
The Disadvantages are :
  • Their inability to support recursion
  • Their storage cannot be shared with local variables

25. What is an ad hoc binding?
 Ad hoc binding is the environment of call statement that passed the subprogram as an actual parameter

34. What is a closure?
 A closure is a subprogram and its referencing environment

___________________________________________________

Problem Set Questions :
5.
void swap(int a, int b){
int temp;
temp = a;
a = b;
b = temp;
}

int main(){
int value = 1, list[5] = {2,4,6,8,10};
swap(value, list[0]);
swap(list[0], list[1]);
swap(value,list[value]);

}
getchar();
return 0;
}

For each of the following parameter passing methods, what are all of the values of the variables value and list after each of the three calls to swap
  • a. Passed by value
  • b. Passed by reference
  • c. Passed by value-result
Answer :
Passed by :
  • a. Value : 1 || List : 2,4,6,8,10
  • b. Value :  6 || List : 4,1,2,8,10
  • c. Value :  6 || List : 4,1,2,8,1


7.
void fun (int first, int second){
first += first;
second += second;
}

void main(){
int list[2] = {3,5};
fun(list[0],list[1]);
printf(“%d%d”,list[0],list[1]);
}

For each of the following parameter passing methods, what are all of the values of the variable list[0] and list[1] after each of the three calls to swap
  • a. Passed by value
  • b. Passed by reference
  • c. Passed by value-result
 Answer :
Passed by :
  • a. list[0] = 3 | list[1] = 5
  • b. list[0] = 4 | list[1] = 6
  • c. list[0] = 4 | list[1] = 6


8. Argue against Java design of not providing operator overloading.
Java design of not providing operator overloading means safety, however, good programmers should be able to understand the concept of operator overloading. Operator overloading itself while can be confusing if used incorrectly(assigning operator + to a function that does something that subtracts or vice versa), Operator overloading itself can be very useful in creating a readable code. Operator overloading allow experienced programmers to be more flexible in their work.


14. Speculate on the issue of allowing function or method overloading in some programming languages. Why are they not allowed by many contemporary languages?
While function/method overloading is flexible, it can also cause confusion if the programmer were to decide to overload a lot of function with different purposes but under the same name.

Chapter 8 of Concept of Programming Languages

Review Question

1. What is the definition of control structure?
A control structure is a control statement and the collection of statements whose execution it controls.


2. What did Bohm and Jocopini prove about flowcharts?
It was proven that all algorithms that can be expressed by flowcharts can be coded in a programming languages with only two control statements: one for choosing between two control flow paths and one for logically controlled iterations.


3. What is the definition of block?
In Ruby, block is a sequence of code, delimited by either breves or the do and and reserved words.


4. What is/are the design issue(s) for all selection and iteration control statements?
There is only one design issue that is relevant to all of the selection and iteration control statements: Should the control structure have multiple entries?


7. Under what circumstances must an F# selector have an else clause?
An F# selector have an “else” clause if the “if” expression does return a value.


9. What are the design issues for multiple-selection statements?

  • What is the form and type of the expression that controls the selection?
  • How are the selectable segments specified?
  • How are the case values specified?
  • How should unrepresented selector expression values be handled, if at all?
  • Is execution flow through the structure restricted to include just a single selectable segment?
14. What are the design issues for all iterative control statements?

  • How is the iteration controlled?
  • Where should the control mechanism appear in the loop statement?
15. What are the design issues for counter-controlled loop statements?

  • What are the type and scope of the loop variable?
  • Should it be legal for the loop variable or loop parameters to be changed in the loop, and if so, does the change affect loop control?
  • Should the loop parameters be evaluated only once, or once for every iteration?
21. What are the design issues for logically controlled loop statements?

  • Should the control be pretest or post-test?
  • Should the logically controlled loop be a special form of a counting loop or a separate statement?
23. What are the design issues for user-located loop control mechanisms?

  • Should the conditional mechanism be an integral part of the exit?
  • Should only one loop body be exited, or can enclosing loops also be exited?


Problem Set

1. What design issues should be considered for two-way selection statements?
The design issues for two-way selectors can be summarized as follows:
• What is the form and type of the expression that controls the selection?
• How are the then and else clauses specified?
• How should the meaning of nested selectors be specified?


4. What are the limitations of implementing a multiple selector from two-way selectors and gotos?
A multiple selector can be built from two-way selectors and gotos, but the resulting structures are cumbersome, unreliable, and difficult to write and read.


5. What are the arguments pro and con, for Java’s approach to specify compound statements in control statements?
• Compound statements are required in control statements when the body of the if or else clause requires multiple statements.
• Java uses braces to form compound statements, which serve as the bodies of if and else clauses.


9. Boolean expressions are necessary in the control statements in Java, as opposed to also allowing arithmetic expressions, as in C++. Give a conditional statement that is correct in C++ but not in Java.

int i=10;
if( i )
{
// block of statements
}
This block of statement is valid in C++ but not in Java.

11. Explain the advantages and disadvantages of the Java switch statement, compared to C++’s switch statement.
The Java variable in the argument of a switch statement can be of type integral ( byte, short etc.), char and String( JDK 1.7 onwards), whereas in C++ the argument can be int or char.


14. State one of the main legitimate needs for gotos.
Premature exits from loops.