Concepts of Programming Language Chapter 15

Friday, June 28th, 2013

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?

Read-evaluate-print loop.

11. What are the two forms of DEFINE?
The simplest form of DEFINE is one used to bind a name to the value of an expression. This form is (DEFINE symbol expression) The general form of such a DEFINE is (DEFINE (function_name parameters) (expression)

13. Why are CAR and CDR so named?
The names of the CAR and CDR functions are peculiar at best. The origin of these names lies in the first implementation of LISP, which was on an IBM 704 computer. The 704’s memory words had two fields, named decrement and address, that were used in various operand addressing strategies. Each of these fields could store a machine memory address. The 704 also included two machine instructions, also named CAR (contents of the address part of a register) and CDR (contents of the decrement part of a register), that extracted the associated fields. It was natural to use the two fields to store the two pointers of a list node so that a memory word could neatly store a node. Using these conventions, the CAR and CDR instructions of the 704 provided efficient list selectors. The names carried over into the primitives of all dialects of LISP.

18. What is tail recursion? Why is it important to define functions that use recursion to specify repetition to be tail recursive?
A function is tail recursive if its recursive call is the last operation in the function. This means that the return value of the recursive call is the return value of the nonrecursive call to the function. It is important to specify repetition to be tail recursive because it is more efficient(increase the efficiency).

19. Why were imperative features added to most dialects of LISP?
LISP began as a pure functional language but soon acquired some important imperative features to increased its execution efficiency.

26. What is type inferencing, as used in ML?
Type inference refers to the automatic deduction of the type of an expression in a programming language. If some, but not all, type annotations are already present it is referred to as type reconstruction.

29. What is a curried function?
Curried functions a function which a new functions can be constructed from them by partial evaluation.

30. What does partial evaluation mean?

Partial evaluation means that the function is evaluated with actual parameters for one or more of the leftmost formal parameters.

32. What is the use of the evaluation environment table?
A table called the evaluation environment stores the names of all implicitly and explicitly declared identifiers in a program, along with their types. This is like a run-time symbol table.

33. Explain the process of currying.

The process of currying replaces a function with more than one parameter with a function with one parameter that returns a function that takes the other parameters of the initial function.

PROBLEM SET

8. How is the functional operator pipeline ( |> ) used in F#?
The pipeline operator is a binary operator that sends the value of its left operand, which is an expression, to the last parameter of the function call, which is the right operand. It is used to chain together function calls while flowing the data being processed to each call.

9. What does the following Scheme function do?
(define ( y s lis)
(cond
(( null? lis) ‘ () )
((equal? s (car lis)) lis)
(else (y s (cdr lis)))
))

y returns the given list with leading elements removed up to but not including the first occurrence of the first given parameter.

10.What does the following Scheme function do?

(define ( x lis)
(cond
(( null? lis) 0 )
(( not(list? (car lis)))
(cond
((eq? (car lis) #f) (x (cdr lis)))
(else (+1 (x (cdr lis))))))
(else (+ (x (car lis)) (x (cdr lis))))

x returns the number of non-#f atoms in the given list

Advertisements

Concepts of Programming Language Chapter 14

Friday, June 28th, 2013

Review Question

6. What is exception propagation in Ada?
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?
– 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?
Version 1.4.

31. What is the use of the assert statement?
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?
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 Language Chapter 13

Friday, June 28th, 2013

Review Question

1. What are the three possible levels of concurrency in programs?
– Instruction level 
– Statement level

– Unit level 

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?
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?
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?
To be a 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?
To mark that the task is finished with its job but is not yet terminated.

34. What does the Java sleep method do?
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?
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?
To create a thread.

57. What is the use of subprograms BeginInvoke and EndInvoke in F#?
To call threads asynchronously.

58. What is the use of the DISTRIBUTE and ALIGN specification of HPC?
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 Language Chapter 12

Friday, June 28th, 2013

Review Question

2. What are the problems associated with programming using abstract data types?
In almost 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.

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

7. What is dynamic dispatch?
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?
It’s 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?
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?
Nope Objective-C doesn’t support it. (It supports only single inheritance).

33. What is the purpose of an Objective-C category?
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?
A primitive values in Java 5.0+ which is implicitly coerced when they are put in object context. This coercion converts the primitive value to an object of the wrapper class of the primitive value’s type.

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

PROBLEM SET

3. Compare the inheritance of C++ and Java.
– In Java, all classes inherit from the Object class directly or indirectly. Therefore, there is always a single inheritance tree of classes in Java, and Object class is root of the tree. In Java, if we create a class that doesn’t inherit from any class then it automatically inherits from Object Class. In C++, there is forest of classes; when we create a class that doesn’t inherit from anything, we create a new tree in forest.
– In Java, members of the grandparent class are not directly accessible.
– The meaning of protected member access specifier is somewhat different in Java. In Java, protected members of a class “A” are accessible in other class “B” of same package, even if B doesn’t inherit from A (they both have to be in the same package)
– Java uses extends keyword for inheritence. Unlike C++, Java doesn’t provide an inheritance specifier like public, protected or private. Therefore, we cannot change the protection level of members of base class in Java, if some data member is public or protected in base class then it remains public or protected in derived class. Like C++, private members of base class are not accessible in derived class.
– Unlike C++, in Java, we don’t have to remember those rules of inheritance which are combination of base class access specifier and inheritance specifier.
– In Java, methods are virtual by default. In C++, we explicitly use virtual keyword.
– Java uses a separate keyword interface for interfaces, and abstract keyword for abstract classes and abstract functions.
– Unlike C++, Java doesn’t support multiple inheritance. A class cannot inherit from more than one class. A class can implement multiple interfaces though.
– In C++, default constructor of parent class is automatically called, but if we want to call parametrized constructor of a parent class, we must use Initalizer list. Like C++, default constructor of the parent class is automatically called in Java, but if we want to call parametrized constructor then we must use super to call the parent constructor

5. Compare abstract class and interface in Java.
-The 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 doesn’t contain any abstract method can be abstract by using abstract keyword.
– Third difference between abstract class and interface in Java is that abstract class are slightly faster than interface because interface involves a search before calling any overridden method in Java. This is not a significant difference in most of cases but if you are writing a time critical application than you may not want to leave any stone unturned.
– Fourth difference between abstract class vs interface in Java is that, interface are better suited for Type declaration and abstract class is more suited for code reuse and evolution perspective.
– Another notable difference between interface and abstract class is that when you add a new method in existing interface it breaks all its implementation and you need to provide an implementation in all clients which is not good. By using abstract class you can provide default implementation in super class.

7. What is one programming situation where multiple inheritance has a significant disadvantage over interfaces?

A situation when there are two classes derived from a common parent and those two derived class has one child.

9. Give an example of inheritance in C++, where a subclass overrides the superclass methods.
class car{
public:
void drive(){
cout << “drive” << endl;
}
};
class bad_car:public class drive{
public:
void drive()
{
cout << “Can’t Drive!” << endl;
}
};

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

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

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

 

Concepts of Programming Language Chapter 11

Friday, June 28th, 2013

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

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

27. Where are all Java methods 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.
Probably no, 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.

Concepts of Programming Language Chapter 10

Friday, June 28th, 2013

Review Question

2. Which of the caller or called saves execution status information?
Called.

4. What is the task of a linker?
To find the files that contain the translated subprograms referenced in that program and load them into memory.

6. What is the difference between an activation record and an activation record instance?

An activation record is the format, or layout, of the moncode part of a subprogram, whereas an activation record instance is a concrete example of an activation record, a collection of data in the form of an activation record.

8. What kind of machines often use registers to pass parameters?
RISC.

11. What is an EP, and what is its purpose?
A point or first address of the activation record instance of the main program. It is required to control the execution of a subprogram.

Problem Set

6. Although local variables in Java methods are dynamically allocated at the beginning of each activation,
under what circumstances could the value of a local variable in a particular activation retain the value of
the previous activation?
If the variable is declared as static. Static modifier is a modifier that makes a variable history – sensitive.

8. Pascal allows gotos with nonlocal targets. How could such statements be handled if static chains were used
for nonlocal variable access? Hint:Consider the way the correct activation record instance of the static
parent of a newly enacted procedure is found(see Section 10.4.2).
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.

 

Concepts of Programming Language Chapter 9

Friday, June 28th, 2013

Review Question

1. What are the three general characteristics of subprograms?
– Each subprogram has a single entry point.
– The calling program unit is suspended during the execution of the called subprogram, which implies that there is only subprogram in execution at any given time.
– Control always returns to the caller when the subprogram execution terminates.

8. What are formal parameters? What are actual parameters?
Formal parameters are the parameters in the subprogram header, actual parameters on the other hand are a list of parameters to be bound to the formal parameters of the subprogram.

10. What are the differences between a function and a procedure?
Functions structurally resemble procedures but are semantically modeled on mathematical function.

11. What are the design issues for subprograms?
– Are local variables statically or dynamically allocated?
– Can subprogram definitions appear in other subprogram definitions?
– What parameter-passing method or methods are used?

24. What is an overloaded subprogram?
The one that has the same name as another subprogram in the same referencing environment.

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

26. What is multicast delegate?
All of the methods stored in a delegate instance are calles in the order in which they were placed in the instance.

32. What exactly is a delegate?
A power and flexibility of method pointers which is increased by making them objects.

34. What is a closure?
A nested subprogram to be called from anywhere in a program.

Problem Sets

3. Argue in support of the templated functions of C++. How is it different from the templated functions of other languages?
It’s different because as C++ differentiates function based on overloading. It is not practical to make multiple function overloading in regard to writability and readability. Instead, creating a template allows a function to receive any datatype as long as the variation is based on the formal parameter definition.

5. Consider the following program written in C syntax:
void swap(int a, int b) {
int temp;
temp = a;
a = b;
b = temp;
}

void main() {
int value =1, list[5]= {2,4,6,8,10};
swap (value,list[0]);
swap(list[0],list[1]);
swap(value,list[value]);
}
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

a. Passed by Value
-value =1 , list[5] = {2,4,6,8,10}
b. Passed by reference
-value =6, list[5] ={4,1,2,8,10}
c. Passed by value-result
-value =6, list[5] ={4,1,2,8,10}

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. Passed by value
b. Passed by reference
c. Passed by value-result

a. 3, 5
b. 6, 10
c. 6, 10

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.

 

Concepts of Programming Language Chapter 8

Friday, June 28th, 2013

Review Question

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

2. What did Bohm and Jocopini prove about flowchart?

Algorithms that can be expressed by flowcharts can be coded in a programming language with only two control statements: one for choosing between two control flow paths and other for logically controlled iterations.

3. What is the definition of block?
An anonymous method that is sent to the method (whose call precedes it) as a parameter

4. What is/are the design issue(s) for all selection and iteration control statements?
Multiple entries, Should the control structure have multiple entries?

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

12. On what previous language was C’s switch statement based?
C’s switch statement is based from the ALGOL 68.

14.  What are the design issues for all iterative control statement
– How is the iteration controlled?
– Where should the control mechanism appear in the loop statement?

21.  What are the design issues for logically controlled loop statements?
whether the control should be pretest/posttest and whether the logically controlled loop should 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?

29. How are iterator implemented in Ruby?
Ruby predefines several iterator methods, such as times and upto for counter-controlled loops and each for simple iterations of arrays and also the hashes too.

 

Problem Sets

1. What design issues should be considered for two-way selection statements?
• 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?

2. Python uses indentation to specify compound statements. Give an example in support of this statement!
Python uses indentation to specify compound statements. For example,
if a > b :
a = b
print “case 7″

3. How can a straightforward grammar for a two-way selector statement lead to the problem of syntactic ambiguity? Give an example!
That ambiguous grammar was as follows:
<if_stmt> →if <logic_expr> then <stmt>
| if <logic_expr> then <stmt> else <stmt>
The issue was when a selection statement is nested in the then clause of a selection statement, it is not clear to which, if an else clause should be associated.

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

Concepts of Programming Language Chapter 7

Monday, May 6th, 2013

Review Question

2.    What is a ternary operator?

Operator with three operands.

 

3.    What is a prefix operator?

Operator that precede their operands.

 

4.    What operator usually has right associativity?

** operator which can be found in Fortran and Ruby.

 

5.    What is a nonassocative operator?

A nonassociative operator means that the expression is illegal.

 

6.    What associativity rules are used by APL?

All operators have equal precedence and all operators associate right to left.

 

8.    Define functional side effect.

Functional side effect occurs when the function changes either one of its parameters or a global variable.

 

10.   What is a conditional expression?

A conditional expression is a statement that contains if-then-else to perform a conditional expression assignment.

 

Problem Sets

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.

4.        Would it be a good idea to eliminate all operator precedence rules and require parentheses to show the desired precedence in expressions? Why or why not?

No, it is not a good idea to eliminate all operator precedence rules.

Although this idea sounds good, but in fact it affects the flexibility provided by the language since only one way is used to show the precedence in expressions. Moreover, using parentheses will future more affects writability and in some cases readability.

5. Should C’s assigning operations (for example, +=) be included in other language (that do not already have them)? Why or why not?
Yes it should be added to other programming language that doesn’t have it yet because the assigning operation is really useful in “for” looping and in recursion. So the addition of assigning operation will increase the orthogonality of its language.
6. Should C’s single-operand assignment form (for example ++count) be included in other language (that do not already have them)? Why or why not?
No it shouldn’t be added, because the use of assigning operation can be replaced the single-operand assignment so it doesn’t increase the complexity of its language
For example the use of  x++ can be replace with x+=1

7.        Describe a situation in which the ad operator in a programming language would not be communicative

An expression such as a + fun(b),

8.        Describe a situation in which the ad operator in a programming language would not be communicative.

Consider the integer expression A + B + C. Suppose the values of A, B, and C are 20,000, 25,000, and -20,000, respectively. Further suppose that the machine has a maximum integer value of 32,767. If the first addition is computed first, it will result in overflow. If the second addition is done first, the whole expression can be correctly computed.

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?
sum1 is 46; sum2 is 48
b. If the operands in the expressions are evaluated right to left?
sum1 is 48; sum2 is 46

 

Concepts of Programming Language Chapter 6

Monday, May 6th, 2013

Review Questions

1.        What is a descriptor?

A descriptor is the collection of the attributes of a variable

6.        What are the advantages of user-defined enumeration types?

The advantages are readability and reliability.

7.        In what ways are the user-defined enumeration types of C# more reliable than those of C++?

C# enumeration types are like those of C++, except that they are never coerced to integer. So, operations on enumeration types are restricted to those that make sense. Also, the range of values is restricted to that of the particular enumeration type.

10.      What happens when a nonexistent element of an array is referenced in Perl?

If you try to append non-existent elements from an array to another one, the initial array will grow as needed, even though the elements to append do not exist.

11.      How does JavaScript  support sparse arrays?

Javascript objects are sparse, and arrays are just specialized objects with an auto-maintained length property (which is actually one larger than the largest index, not the number of defined elements) and some additional methods.

13.      What languages support array slices with stepsizes?

Ruby, Python, Perl.

14.      What arrays initialization feature is available in Ada that is not available in other common imperative languages?

Ada provides two mechanisms for initializing arrays in the declarations statements: by listing them in the order in which they are to be stored, or by directly assigning them to an index position using the => operator, which in Ada is called an arrow.

15.      What is an aggregate constant?

A parenthesized lists of values.

16.      What array operations are provided specifically for single-dimensioned arrays in Ada?

Catenation specified by the ampersand (&).

18.      What is an access function for an array?

Access function maps subscript expressions to an address in the array

20.      What is the structure of an associative array?

An associative array is an unordered collection of data elements that are indexed by an equal number of values called keys. User-defined keys must be stored.

21.      What is the purpose of level numbers in COBOL records?

COBOL uses level numbers to show nested records; others use recursive definition

24.      Are the tuples of Python mutable?

Python includes an immutable tuple type

25.      What is the purpose of an F# tuple pattern?

A tuple pattern is simply a sequence of names, one for each element of the tuple , with or without the delimiting parentheses.

26.      In what primarily imperative language do lists serve as arrays?

Python

Problem Sets

1.        What are the arguments for and against four signed integer sizes in Java?

bytes (1 byte), short(2 bytes), integer (4 bytes), long (8 bytes). As a result, depending on the domain of the variable required, data types are used.

2.         How are negative integers stored in memory?

Negative integer stored in memory by turning the value into binary and makes the compliment of its binary.
For example : integer 1 in binary is 0001 to get -1 the computer uses the compliment so it will be 1110. The 1110 binary might be 14 or -1 depends on the data type.
8. What are the differences between the reference type variable of C++ and those of Java?
The differences between the reference type variable of C++ and those of Java are first in Java we can’t actually get to and manipulate the underlying value of a reference in Java but in C we can manipulate it. Second in java references are strictly controlled than in C. Third in Java reference will be implemented as pointers, but that is not required by the specification in the other hand C reference is not implemented as pointer.

11.      In the Burroughs Extended ALGOL language, matrices are stored as a single-dimensional array of pointers to the rows of the matrix, which are treated as single-dimensional arrays of values. What are the advantages and disadvantages of such a scheme?

The advantage of this scheme is that accesses that are done in order of the rows can be made very fast; once the pointer to a row is gotten, all of the elements of the row can be fetched very quickly. If, however, the elements of a matrix must be accessed in column order, these accesses will be much slower; every access requires the fetch of a row pointer and an address computation from there. Note that this access technique was devised to allow multidimensional array rows to be segments in a virtual storage management technique. Using this method, multidimensional arrays could be stored and manipulated that are much larger than the physical memory of the computer.

19.         Any type defined with typedef is type equivalent to its parent type. How does the use of typedef differ in C and C++?
Typedef in C uses struct to do typedef, with the fortmat typedef struct name_of struct; Typedef in c++ we don’t need to uses the keyword typedef and it has a format typedef existing_type new_type_name
21.          In what way dynamic checking is better than static type checking?
Dynamic checking occurs when type information is used at runtime. In the other hand static type checking means that type checking occurs at compile time. It is better to do dynamic checking because it will be more reliable and more relevant to the information that is used during the runtime