Sunday, June 16, 2013

Concepts of Programming Languages – Chapter 15


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

Concepts of Programming Languages – Chapter 14


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.

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.

2.Describe the approach for the detection of subscript range errors used in C and Java.
In C subscript ranges are not checked. Java compilers usually generate code to check the correctness of every subscript expression. If any exception generates, then an unchecked exception is thrown.

6.In languages without exception-handling facilities, it is common to have most subprograms include an “error” parameter, which can be set to some values 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 languages without exception-handling facilities, we could send an error-handling procedure as parameter to each procedure that can detect errors than must be handled. What disadvantage 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.

14. Summarize the arguments in favor of the termination and resumption models of continuation.
The resumption model is useful when the exception is only an unusual condition, rather than an error. The termination model is useful when the exception is an error and it is highly unlikely that the error can be corrected so that execution could continue in some
useful way.

Concepts of Programming Languages – Chapter 13


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.

Concepts of Programming Languages – Chapter 12


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?
Message protocol is the entire collection of methods of an object.

5. What is an overriding method?
Overriding method is method that overrides the inherited method.

7. What is dynamic dispatch?
Dynamic dispatch is the third characteristic (after abstract data types and inheritance) of object-oriented programming language which is a kind of polymorhphism provided by the dynamic binding of messages to method definitions.

12. From where are Smalltalk objects allocated?
Smalltalk objects are allocated from the heap and are referenced through reference variables, which are implicitly dereferenced.

15. What kind of inheritance, single or multiple, does Smalltalk support?
Smalltalk supports single inheritance; it does not allow multiple inheritance.

19. How are C++ heap-allocated objects deallocated?
C++ heap-allocated objects are deallocated using destructor.

29. Does Objective-C support multiple inheritance?
No Objective-C doesn’t support it. (It supports only single inheritance).

33. What is the purpose of an Objective-C category?
The purpose of an Objective-C category is to add certain functionalities to different classes and also to provide some of the benefits of multiple inheritance, without the naming collisions that could occur if modules did not require module names on their functions.

38. What is boxing?
Boxing is primitive values in Java 5.0+ which is implicitly coerced when they are put in object context. This coercion converts the primitive value to an object of the wrapper class of the primitive value’s type.

39. How are Java objects deallocated?
By implicitly calling a finalizemethod when the garbage collector is about to reclaim the storage occupied by the object.


Problem Set

3. Compare the inheritance of C++ and Java.
- In Java, all classes inherit from the Object class directly or indirectly. Therefore, there is always a single inheritance tree of classes in Java, and Object class is root if 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 because Java 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 don’t contain any abstract method can be abstract by using abstract keyword.
- Third difference between abstract class and interface in Java is that abstract class are slightly faster than interface because interface involves a search before calling any overridden method in Java. This is not a significant difference in most of cases but if you are writing a time critical application than you may not want to leave any stone unturned.
- Fourth difference between abstract class vs interface in Java is that, interface are better suited for Type declaration and abstract class is more suited for code reuse and evolution perspective.
- Another notable difference between interface and abstract class is that when you add a new method in existing interface it breaks all its implementation and you need to provide an implementation in all clients which is not good. By using abstract class you can provide default implementation in super class.

7. What is one programming situation where multiple inheritance has a significant disadvantage over interfaces?
A situation when there are two classes derived from a common parent and those two derived class has one child.

9. Give an example of inheritance in C++, where a subclass overrides the superclass methods.
class plane{
public:
 void fly(){
  cout << “fly” << endl;
 }
};
class jet: public class plane{
public:
 void fly()
  {
   cout << “Fly! Rocket jet activated!” << endl;
  }
};

10. Explain one advantage of inheritance.
Inheritance offers a solution to both the modification problem posed by abstract data type reuse and the program organization problem. If a new abstract data type can inherit the data and functionality of some existing type, and is also allowed to modify some of those entities and add new entities, reuse and is also allowed to modify some of those entities and add new entities, reuse is greatly facilitated without requiring change to the reused abstract data type. Programmers can begin with an existing abstract data type and design a modified descendant of it to fit a new problem requirement.
Furthermore, inheritance provides a framework for the definition of hierarchies of related classes that can reflect the descendant relationship in the problem space.

12. Compare inheritance and nested classes in C++. Which of these supports an is-a relationship?
Inheritance is where one class (child class) inherits the members of another class (parent class). Nested class is a class declared entirely within the body of another class or interface.
Inheritance does.

17. What are the different options for object destruction in Java?
There is no explicit deallocation operator. A finalize method is implicitly called when the garbage collector is about to reclaim the storage occupied by the object.

Saturday, June 15, 2013

Concepts of Programming Languages – Chapter 11


Review Question

2. Define abstract data type.
Data type that satisfies the following conditions:
-The representation of objects of the type is hidden from the program units that use the type, so the only direct operations possible on those objects are those provided in the type’s definition.
-The declarations of the type and the protocols of the operations on objects of the type, which provide the type’s interface, are contained in a single syntactic unit. The type’s interface does not depend on the representation of the objects or the implementation of the operations. Also, other program units are allowed to create variables of the defined type.

8. What is the difference between private and limited private types in Ada?
Limited private is more restricted form and objects of a type that is declared limited private have no built-in operations.

10. What is the use of the Ada with clause?
With clause makes the names defined in external packages visible; in this case Ada. Text_IO, which provides functions for input of text.

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

12. What is the fundamental difference between a C++ class and an Ada package?
Ada packages are more generalize encapsulations that can define any number of types.

15. What is the purpose of a C++ destructor?
The purpose of a C++ desctructor is as a debugging aid, in which case they simply display or print the values of some or all of the object’s data members before those members are deallocated.

16. What are the legal return types of a desctructor?
Destructor has no return types and doesn’t use return statements.

21. What are initializers in Objective-C?
The initializers in Objective-C are constructors.

22. What is the use of @private and @public directives?
The use is to specify the access levels of the instance variables in a class definition.

27. Where are all Java methods defined?
All Java methods are defined in a class.

30. What is a friend function? What is a friend class?
a “friend” of a given class is allowed access to public, private, or protected data in that class. Normally, function that is defined outside of a class cannot access such information.

Class that can access the private and protected members of the class in which it is declared as a friend. On declaration of friend class all member function of the friend class become friends of the class in which the friend class was declared.

43. What is a C++ namespace, what is its purpose?
In general, a namespace is a container for a set of identifiers and allows the disambiguation of homonym identifiers residing in different namespaces. The purpose is to help programs manage the problem of global namespace.


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

Concepts of Programming Languages - Chapter 10


Review Questions

1. What are the two reasons why implementing subprograms with stack-dynamic local variables is more difficult than implementing simple sub-programs?
A stack-dynamic local variable is more complex activation records. The compiler must generate code to cause implicit allocation and de-allocation of local variables.
Recursion must be supported (adds the possibility of multiple simultaneous activations of a subprogram).

2. What is the difference between an activation record and activation record instance?
The Format, or layout, of the non-code part of a subprogram is called an activation record.
An activation record stores all the information about subprogram calls, activation records stores the following data (in the following order).
Return address
Static link – to the static parent (where the subprogram is declared).
Dynamic link – to the caller of this subprogram.
Parameters
Local variables.

4. What are the two steps in locating a nonlocal variable in a static-scoped language with stack-dynamic local variables and nested subprograms?
Find the correct activation record instance.
Determine the correct offset within that activation record instance.

5. Define static chain, static depth, nesting_depth, and chain offset.
A static chain is a chain of static links that connects certain activation record instances.
Static_depth is an integer associated with a static scope representing the scope’s nesting depth.
The chain_offset or nesting_depth of a non-local reference is the difference between the static_depth of the reference and that of the scope where it is declared.

6. What are the two potential problems with the static chain methods?
A nonlocal reference is slow if the number of scopes between the reference and the declaration of the referenced variable is large.
Time-critical code is difficult, because the costs of nonlocal references are not equal, and can change with code upgrades and fixes.

7. What is display?
One alternative to static chain is to use a display, for this approach, the static links are collected in a single array called a display. Display uses a pointer array to store the activation records along the static chain.

10. Explain the two methods of implementing block?
Blocks are treated as parameter less subprograms that are always called from the same place in the program.
Block can also be implemented in a different and somewhat simpler and more efficient way. The maximum amount of storage required for block variables at any time during the exaction of program can be statically determined, because block are entered and exited in strictly textual order.

11. Describe the deep access method of implementing dynamic scoping?
Deep Access – nonlocal references are found by searching the activation record instances on the dynamic chain. Length of chain cannot be statically determined every activation record instance must have variable names.

12. Describe the shallow access method of implementing dynamic scoping?
In case of shallow access names and values are stored in a global table. Using this method, space is allocated for every variable name that is in the program (one space for variable temp though there might be several declarations of temp in the different methods). When a sub-routine is called it saves the current value of the variable and replaces it with the value in its current scope and restores the value of the variable while exiting.

14. Compare the efficiency of the deep access method to that of the shallow access method, in term of both call and nonlocal access?
The deep access methods provides fast subprogram linkage, but references to nonlocal, especially references to distant nonlocals (in term of the call chain), are costly. The shallow access methods provide much faster references to nonlocals, especially distant nonlocals, but are more costly in term of subprogram linkage.


Problem Set

7. It stated in this chapter that when nonlocal variables are accessed in a dynamic-scoped language using the dynamic chain, variable names must be stored in the activation records with the values. If this were actually done, every nonlocal access would require a sequence of costly string comparisons on names. Design an alternative to these string comparisons that would be faster.
One very simple alternative is to assign integer values to all variable names used in the program. Then the integer values could be used in the activation records, and the comparisons would be between integer values, which are much faster than string comparisons.

8. Pascal allows gotos with nonlocal targets. How could such statements be handled if static chains were used for nonlocal variable access?
Following the hint stated with the question, the target of every goto in a program could be represented as an address and a nesting_depth, where the nesting_depth is the difference between the nesting level of the procedure that contains the goto and that of the procedure containing the target. Then, when a goto is executed, the static chain is followed by the number of links indicated in the nesting_depth of the goto target. The stack top pointer is reset to the top of the activation record at the end of the chain.

9. The static-chain method could be expanded slightly by using two static links in each activation  record instance where the  second points to the static grandparent activation record instance. How would this approach affect the time required for subprogram linkage and nonlocal references?
Including two static links would reduce the access time to nonlocals that are defined in scopes two steps away to be equal to that for nonlocals that are one step away. Overall, because most nonlocal references are relatively close, this could significantly increase the execution efficiency of many programs.

11. If a compiler uses the static chain approach to implementing blocks, which of the entries in the activation records for subprograms are needed in the activation records for blocks?
There are two options for implementing blocks as parameterless subprograms: One way is to use the same activation record as a subprogram that has no parameters. This is the most simple way, because accesses to block variables will be exactly like accesses to local variables. Of course, the space for the static and dynamic links and the return address will be wasted. The alternative is to leave out the static and dynamic links and the return address, which saves space but makes accesses to block variables different from subprogram locals.

Saturday, June 8, 2013

Concepts of Programming Languages - Chapter 9


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.

Monday, April 8, 2013

Concepts of Programming Languages - Chapter 7


Review Questions

2. What is a ternary operator?
A ternary operator is an operator that has three operands.

3. What is a prefix operator?
A prefix operator is an operator that precedes the operands.

4. What operator usually has right associativity?
Exponentiation operator.

5. What is a nonassociative operator?
A nonassociative operator is an operator that needs to be parenthesized to show the desired order to become legal.

8. Define functional side effect.
Functional side effect is a side effect that occurs when the function changes either one of its parameters or a global variable.

11. What is an overloaded operator?
An overloaded operator is an arithmetic operator that is often used for more than one purpose.

24. What two languages include multiple assignments?
Ruby and Perl.

28. What is a cast?
Explicit type conversion.


Problem Set

1. When might you want the compiler to ignore type differences in an expression?
Suppose Type1 is a subrange of Integer. It may be useful for the difference between Type1 and Integer to be ignored by the compiler in an expression.

3. Do you think the elimination of overloaded operators in your favorite language would be beneficial? Why or why not?
Yes. Because eliminating overloaded operators will increase readability and prevent compiler confusion in choosing the correct meaning of the operator.

7. Describe a situation in which the add operator in a programming language would not be commutative.
An expression such as i + fun(j)

13. Let the function fun be defined as

int fun (int *k){
 *k += 4;
 return 3 * (*k) – 1;
}

Suppose fun is used in a program as follows:

void main(){
 int i = 10, j = 10, sum1, sum2;
 sum1= (i / 2) + fun(&i);
 sum2 = fun (&j) + (j / 2);
}

What are the values of sum1 and sum2
a. if the operands in the expressions are evaluated left to right?
b. if the operands in the expressions are evaluated right to left?

a. left to right: sum1 is 46; sum2 is 48
b. right to left: sum1 is 48; sum2 is 46

15. Explain why it is difficult to eliminate functional side effects in C.
All functions in C are subprograms and each of them return only one value.To return more that one value, we have to use parameters and if the parameters are pointers it may change the value of variables. Another problem is if the function changes the value of a global variable, it may affect the whole program.

20. Consider the following C program:

int fun (int *i){
 *i += 5;
 return 4;
}

void main(){
 int x = 3;
 x = x + fun( &x );
}

What is the values of x after the assignment statement in main, assuming
a. operands are evaluated left to right.
b. operands are evaluated right to left.

a. 7
b. 12


Sunday, April 7, 2013

Concepts of Programming Languages - Chapter 6


Review Questions

1. What is a descriptor?
A descriptor is the collection of the attributes of a variable.

3. What are the design issues for character sting types?
- Should strings be simply a special kind of character array or a primitive type?
- Should strings have static or dynamic length?

4. Describe the three string length options.
- Static length string, the length can be static and set when the string is created.
- Limited dynamic length strings, allow strings to have varying length up to a declared and fixed maximum set by the variable’s definition.
- Dynamic length strings, allow strings to have varying length with no maximum.

11.How does JavaScript support sparse arrays?
JavaScript sparse arrays means that the subscript values need not be contiguous.

12. What languages support negative subscripts?
Perl.

13. What languages support array slices with stepsizes?
Phyton, Perl, and Ruby.

23. What is the primary difference between a record and a tuple?
The elements of a record are named while the elements of a tuple are not named.

24. Are the tuples of Python mutable?
No.

27. What is the action of the Scheme function CAR?
The function CAR returns the first element of its list parameter.

28. What is the action of the F# function tl?
The function tl returns all elements of its list parameter except the first one.

32. What are the design issues for unions?
- Should type checking be required? Note that any such type checking must be dynamic.
- Should unions be embedded in records?

33. Are the unions of Ada always type checked?
Yes.

34. Are the unions of F# discriminated?
Yes.

43. What is a compatible type?
A compatible type is one that either is legal for the operator or is allowed under language rules to be implicitly converted by compiler-generated code to a legal type.


Problem Set

7. Compare the pointer and reference type variable in C++.
A C++ reference type variable is a constant pointer that’s always implicitly dereferenced.

9. C provides two derived data types both for name and structure type equivalence: struct and union. Makes a study on when to use struct type variables and union type variables.
If all data members of the variables are to be used at once then struct type variables are required, otherwise union type variables should be used.

21. In what way is dynamic type checking better than static type checking?
Dynamic type checking detects error at compile time and it is better than detecting error at run time.

Concepts of Programming Languages - Chapter 5


Review Questions

2. What is the potential danger of case-sensitive names?
It affects the writability of a program because the need to remember specific case usage makes it more difficult to write correct programs.

3. In what way are reserved words better that keywords?
Reserved words are better that keywords because the ability to redefine keywords are confusing.

4. What is an alias?
Alias is a variable name that can be used to access the same memory loaction of another variable name.

6. What is the l-value of a variable? What is the r-value?
R-value is the address of a variable.
L-value is the variable's value.

7. Define binding and  binding time.
Binding is an association between an attribute and an entity.
Binding time is the time at which a binding takes place.

8. After language design and implementation [what are the four times binding can take place in a program?]
Type bindings, static type bindings, dynamic type bindings, storage bindings.

18. What is a block?
A block is a section of code which variables storage is allocated when the section is entered and deallocated when the section is exited.

23. What are the advantages of named constants?
To improve readability, to parameterize a program.


Problem Set

1. Decide which of the following identifier names is valid in C language. Support your decision.
_Student
Student
student123
In C language, underscore (_) and uppercase/lowercase letter are allowed to start identifier names, digits and symbols aren't allowed. "int" is a reserved word for integer so it's not allowed.


2. What is l-value? Write a statement in C language which gives the compile time error “l-value required”.
The address of a variable is called its l-value.
Example:
int i = 10, j;
j = 9--; //error C2105: '--' needs l-value


4. Why is the type declaration of a variable necessary? What is the value range of the int type variable in Java?
Because the type declaration of a variable determines the range of values the variable can store and the set of operations that are defined for values of the type.
-2147483648 to 2147483647.

5. Describe a situation each where static and dynamic type binding is required.
Static binding is required if we need the bindings to occur first before the run time begins and remains unchanged throughout program execution.
Dynamic binding is required if we need the binding to occur first during run time or can change in the course of program execution.

Tuesday, March 26, 2013

Concepts of Programming Languages - Chapter 3


Review Questions

1. Define syntax and semantics.
Syntax is the form or structure of the expressions, statements, and program units.
Semantics is the meaning of the expressions, statements, and program units.

2. Who are language descriptions for?
The language descriptions is important for the programming language implementers to determine how the expressions, statements, and program units of a language are formed, and also their intended effect when executed.

3. Describe the operation of a general language generator.
A language generator is a device that can be used to generate the sentences of a language. We can think of the generator as having a button that produces a sentence of the language every time it is pushed. Because the particular sentence that is produced by a generator when its button is pushed is unpredictable, a generator seems to be a device of limited usefulness as a language descriptor.

7. What three extensions are common to most EBNFs?
Three extensions are commonly included in the various versions of EBNF. The first extension denotes an optional part of an RHS, which is delimited by brackets. The second extension is the use of the brackets in an RHS to indicate that the enclosed part can be repeated indefinitely or left out altogether. And the third extension deals with multiple-choice options.

10. What is the difference between a synthesized and an inherited attribute?
The attributes are divided into two groups: synthesized attributes and inherited attributes. The synthesized attributes are the result of the attribute evaluation rules, and may also use the values of the inherited attributes. The inherited attributes are passed down from parent nodes.

12. What is the primary use of attribute grammar?
Attribute grammar is primary used to provide complete descriptions of the syntax and static semantics of programming languages.

21. When is a grammar rule said to be left recursive?
When a grammar rule has its LHS also appearing at the beginning of its RHS, the rule is said to be left recursive. This left recursion specifies left associativity.

22. Give an example of an ambiguous grammar.
<assign> -> <id> = <expr>

<id> -> A | B | C

<expr> -> <expr> + <expr>

| <expr> * <expr>

|  (  <expr>  )

| <id>

23. On what branch of mathematics is axiomatic semantic based?
Axiomatic semantics, thus named because it is based on mathematical logic.

24. Give an unambiguous grammar for if-then-else.
<if_stmt> -> if <logic_expr> then <stmt>

if <logic_expr> then <stmt> else <stmt>


Problem Set

1. Syntax error and semantic error are two types of compilation error. Explain the difference between the two in a program with examples.
Syntax error is a code error and semantic error is a logical error.
An example of syntax error, for example in C, is forget to put semicolon
assume that printf("Hello world");
It is a syntax error if we make printf("Hello world")
An example of semantic error is: const int pi = 123;
It is syntactically correct but logically incorrect.

3. Rewrite the BNF of Example 3.4 to represent operator – and operator / instead of operator + and operator *.
<assign> -> <id> = <expr>
<id> -> A | B | C
<expr> -> <expr> - <term>
|<term>
<term> -> <term> * <factor>
|<factor>
<factor> -> ( <expr> )
|<id>

8. Prove that the following grammar is ambiguous:
<S> -> <A>
<S> -> <A> * <A> | <id>
<id> -> x | y | z
The grammar is ambiguous, because the grammar generates different parse trees.

9. Modify the grammar of Example 3.4 to add a unary minus operator that has higher precedence than either + or *.
Assume that the operators can precede any operand
<factor> -> <id>
with
<factor> -> + <id>
| - <id>

10. Describe, in English, the language defined by the following grammar:
<S> -> <X><Y>
<X> -> x<X> | x
<Y> -> y<Y> | y
x can be followed by one or more than one x, then followed by one or more than one y.

11. Consider the following grammar:
<S> -> <A> a <B> b
<A> -> <A> b | b
<B> -> a <B> | a
Which of the following sentences are in the language generated by this
grammar?
a. bbaabb
d. abaabb

12. Consider the following grammar:
<S> -> a <S> c <B> |<A> |b
<A> -> c <A> |c
<B> -> d |<A>
Which of the following sentences are in the language generated by this
grammar:
b. accbcbccc

18.  What is a fully attributed parse tree?
A fully attributed parse tree is a condition when all the attributed values in parse tree have been computed.

23. Compute the weakest precondition for each of the following sequences of assignment statements and their postconditions:
a. a = 2 * (b - 1) - 1 {a > 0}
2 * (b - 1) - 1 > 0
2*b - 2 > 1
2*b > 3
b > 3/2

b. b = (c + 10) / 3 {b > 6}
(c + 10) / 3 > 6
c + 10 > 18
c > 8

c. a = a + 2 * b - 1 {a > 1}
a + 2 * b - 1 > 1
a + 2 * b > 2
2 * b > 2 - a
b > (2 - a) / 2

d. x = 2 * y + x - 1 {x > 11}
2 * y + x - 1 > 11
2 * y + x > 12

24. Compute the weakest precondition for each of the following sequences of assignment statements and postconditions:
a. a = 2 * b + 1;
b = a - 3
{b < 0}

a - 3 < 0
a < 3

2 * b + 1 < 3
2 * b < 2
b < 1

b. a = 3 * (2 * b + a);
b = 2 * a - 1
{b > 5}

2 * a - 1 > 5
2 * a > 6
a > 3

3 * (2 * b + a) > 3
6 * b + 3 * a > 3
2 * b + a > 1
2 * b > 1 - a
b > (1 - a)/2

Monday, March 25, 2013

Concepts of Programming Languages - Chapter 1


Review Questions

3. What programming language has dominated scientific computing over
the past 50 years?
Fortran

4. What programming language has dominated business applications over
the past 50 years?
COBOL

5. What programming language has dominated artificial intelligence over
the past 50 years?
LISP

6. In what language is most of UNIX written?
C

21. What two programming language deficiencies were discovered as a
result of the research in software development in the 1970s?
Incompleteness of type checking and inadequacy of control statements

22. What are the three fundamental features of an object-oriented programming
language?
Encapsulation, inheritance, polymorphism

23. What language was the first to support the three fundamental features of
object-oriented programming?
Smalltalk

25. What are the three general methods of implementing a programming
language?
Compilation, pure interpretation, hybrid implementation system

26. Which produces faster program execution, a compiler or a pure
interpreter?
A compiler

29. Whhat is a hybrid implementation system?
An implementation that translates high-level language programs to an intermediate language designed to allow easy interpretation so that it is faster than pure interpretation because the source language statements are decoded only once.


Problem Set

1. Do you believe our capacity for abstract thought is influenced by our
language skills? Support your opinion.
Yes, because by having programming language skills we know the differences of the languages and we can choose which kind of language that is more suitable to the algorithm we are making so the algorithm will be a simple one.

2. Who is said to be the first programmer in human history? Use the Internet for help.
Ada Lovelace

4. In what way do the languages for scientific applications differ from the languages for business applications? Support your view.
Scientific applications used relatively simple data structures but required large numbers of floating-point arithmetic computations. Business languages are characterized by facilities for producing elaborate reports, precise ways of describing and storing decimal numbers and character data, and the ability to specify decimal arithmetic operations.

7. Java uses a semicolon to mark the end of all statements. What are the advantages for and against this design?
Adv: using semicolon is a simplicity that it closes every statement.
Disadv: sometimes we forget to put semicolon on a statement that it creates compilation error.

10. Make a comparative study of the cost of software and hardware.
The cost of hardware was higher than software in the past, but now they're the opposite.

12. Can we call any programming language complete, in your opinion? Why or why not?
No, because each programming language has its own characteristics and is used for a specific purpose that differs it from other programming languages


Edited on 25/03/2013

Sunday, March 10, 2013

Concepts of Programming Languages - Chapter 2


Review Questions

1. In what year was Plankalkül designed? In what year was that design
published?
1943, 1972

3. What does Plankalkül mean?
Program Calculus

5. What is the number of bits in a single word of the UNIVAC I's memory? How are the bits grouped?
72, they are grouped as 12 six-bit bytes

7. Who developed the Speedcoding system for the IBM 701?
John Backus

8. Who developed Short Code? Why is Short Code called automatic programming?
John Mauchly. Because it clearly simplified the programming process.

9. Under what environmental consideration was Fortran developed? Which is the first version of Fortran?
- Computers had small memories and were slow and relatively unreliable
- the primary use of computers was for scientific computations
- there were no existing efficient and effective ways to program computers
- because of the high cost of computers compared to the cost of programmers, speed of the generated object code was the primary goal of the first Fortran compilers.
Fortran 0

10. What was the most significant feature added to Fortran I to get Fortran II?
Independent compilation of subroutines

11. What control flow statements were added to Fortran IV to get Fortran 77?
Character string handling, logical loop control statements, and an If with an optional Else clause

12. Which version of Fortran was the first to have any sort of dinamic variables?
Fortran 4

13. Which version of Fortran was the first to have character string handling?
Fortran 77

14. Why were linguists interested in artificial intelligence in the late 1950s?
Linguists were concerned with natural language processing

17. What dialect of LIST is used for introductory programing courses at some universities?
Scheme

22. On what language was COBOL based?
English

23. In what year did the COBOL design process begin?
May 28 and 29, 1959

26. Which data type does the original BASIC language support?
Floating point

28. PL/I was designed to replace what two languages?
Fortran and COBOL

46. What is the primary application for Objective-C?
To write the NeXT computer system software


Problem Set

6. Make an educated guess as to the most common syntax error in C programs.
- Semicolon (;) missing.
- Unmatched parentheses.
- Undeclared variables.
- Prototype function mismatch.

7. LISP began as a pure functional language but gradually acquired more and more imperative features. Why?
To increase its execution efficiency.

8. Describe in detail the two most important reasons, in your opinion, why Speedcoding did not became a very widely used language.
Speedcoding system was an interpreter so that the running time of a program that was written with the help of Speedcoding was usually ten to twenty times that of machine code.
Speedcoding interpreter took much memory to execute the program and it wasn't efficient.

14. What are the arguments both for and against the idea of a typeless language?
Typeless language is highly flexible for the programmer, any storage location can be used to store any type value.
Type checking can't be applied so the programmer has to make sure that the statements are correct.

15. Are there any nonprochedural programming languages other that Prolog?
No

16. What is your opinion of the argument that languages that are too complex are too dangerous to use, and we should therefore keep all languages small and simple?
Languages that are too complex and too dangerous must be avoided because they will be difficult to learn and they may cause so many errors because of the complexity. We should keep all languages small and simple so we can learn them fast and we know hot to use them specifically.

22. Explain two reasons why pure interpretation is an acceptable implementation method for several recent scripting languages.
- Pure interpretation is platform independent
- Interpretation gives the fastest turnaround from script to execution

24. Why, in your opinion, do new scripting languages appear more frequently than new compiled languages?
Because scripting languages usually are simpler and focused on specific applications.


Edited on 25/03/2013