Jumat, 28 Juni 2013

Chapter 16

Chapter 16

Review Question


1. What are the three primary uses of symbolic logic in formal logic ?
- to express propositions, to express the relationships between propositions, and to
describe how new propositions can be inferred from other propositions that
are assumed to be true.
2. What are the two parts of a compound term ?- functor and and ordered list of of parameters
3. What are the two modes in which a proposition can be stated ?- one in which a proposition is defined to be true and one in which that the proposition is something to be determined.
4. What is general form of a proposition in clausal form ?-B1 U B2 U . . . U Bn C A1 n A2 n . . . n Am
5. What are antecedents ? Consequents ?- Antecedents are right side of a clausal form proposition. Consequent is left side of a clausal form propositions
6. Give general definitions of resolution and unification- Resolution : inference rule that allows inferred propositions to be computed from given propositions, thus providing a method with potential application to automatic theorem proving.
Unification : Process of determining useful values for variables.
7. What are the forms of Horn clauses?Headed and headless.
9. What does it mean for a language to be nonprocedural?Programs do not state now a result is to be computed, but rather the form of the result
Problem Set
1. Compare the concept of data typing in Ada with that of Prolog.Ada variables are statically bound to types.  Prolog variables are bound to types only when they are bound to values.  These bindings take place during execution and are tempoarary.
2. Describe how a multiple-processor machine could be used to implement resolution. Could Prolog, as currently defined, use this method?On a single processor machine, the resolution process takes place on the rule base, one rule at a time, starting with the first rule, and progressing toward the last until a match is found.  Because the process on each rule is independent of the process on the other rules, separate processors could concurrently operate on separate rules.  When any of the processors finds a match, all resolution processing could terminate.
8. Critically comment on the following statement : “ Logic programs are nonprocedural”- It is true, because logical programs use lots of different processes based on its conditions. If a certain logical requirement is true, then a program will execute the corresponding process, instead of procedurally executing the statements.
9. From a book on Prolog, learn and write a description of a monkey-banana prolem. Why does Prolog allow this problem to exist in its implementation ?- The problem is defined as this : a monkey is in a room. Suspended from the ceiling is a bunch of bananas, beyond the monkey’s reach. However, in the room there are also a chair and a stick. The ceiling is just the right height so that a monkey standing on a chair could knock the bananas down with the stick. The monkey knows how to move around, carry other things around, reach for the bananas, and wave a stick in the air. What is the best sequence of actions for the monkey?
It exists to create a variation in output of Prolog. As Prolog is an AI programming language, a variation might be needed in AI output to make them respond relevant to the situation.


Chapter 15

Chapter 15

Review Questions

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

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.
27. What is the use of the fn reserved word in ML?
 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.

29. What is a curried function?Curried functions are interesting and useful because 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.

31. Define reader macros.Reader macros or read macros, that are expanded during the reader phase of a LISP language processor. A reader macro expands a specific character into a string of LISP code. For example, the apostrophe in LISP is a read macro that expands to a call to QUOTE. Users can define their own reader macros to create other shorthand constructs.

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

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

Problem Set

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

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

10. What does the following Scheme function do?(define (x lis)
(cond
((null? lis) 0)
((not (list? (car lis)))
(cond
((eq? (car lis) #f) (x (cdr lis)))
(else (+ 1 (x (cdr lis))))))
(else (+ (x (car lis)) (x (cdr lis))))
x returns the number of non-NIL atoms in the given list.

Chapter 14

Chapter 14


Review Questions

1. Define exception, exception handler, raising an exception, disabling an exception, continuation, finalization, and built-in exception.Answer: An exception is an unusual event that is detectable by either hardware or software and that may require special processing. The special processing that may be required when an exception is detected is called exception handling. The processing is done by a code unit or segment called an exception handler. An exception is raised when its associated event occurs. In some situations, it may be desirable to ignore certain hardware-detectable exceptions—for example, division by zero—for a time. This action would be done by disabling the exception. After an exception handler executes, either control can transfer to somewhere in the program outside of the handler code or program execution can simply terminate. We term this the question of control continuation after handler execution, or simply continuation. In some situations, it is necessary to complete some computation regardless of how subprogram execution terminates. The ability to specify such a computation is called finalization. Built-in exceptions have a built-in meaning, it is generally inadvisable to use these to signal program-specific error conditions.  Instead we introduce a new exception using an exception declaration, and signal it using a raise expression when a run-time violation occurs.  That way we can associate specific exceptions with specific pieces of code, easing the process of tracking down the source of the error.

2. When is an exception thrown or raised?Answer: The exception thrown or raised when there is throw clause of a method lists that have checked exception which could throw and does not handle.


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.

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 value representing “OK” or some other value representing “error in procedure.” What advantage does a linguistic exception-handling facility like that of Ada have over this method?
There are several advantages of a linguistic mechanism for handling exceptions, such as that found in Ada, over simply using a flag error parameter in all subprograms.  One advantage is that the code to test the flag after every call is eliminated.  Such testing makes programs longer and harder to read.  Another advantage is that exceptions can be propagated farther than one level of control in a uniform and implicit way.  Finally, there is the advantage that all programs use a uniform method for dealing with unusual circumstances, leading to enhanced readability.

7. In a language without exception handling facilities, we could send an error-handling procedure as a parameter to each procedure that can detect errors that must be handled. What disadvantages are there to this method?
There are several disadvantages of sending error handling subprograms to other subprograms. One is that it may be necessary to send several error handlers to some subprograms, greatly complicating both the writing and execution of calls. Another is that there is no method of propagating exceptions, meaning that they must all be handled locally. This complicates exception handling, because it requires more attention to handling in more places.

Chapter 13

Chapter 13

Review Questions

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.

Chapter 12

Chapter 12


Review Questions



4. What is message protocol?Message protocol is the entire collection of methods of an object.


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


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


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


11. What is the message protocol of an object?The message protocol of an objects are all the methods.


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.


18. From where can C++ objects be allocated?The objects of C++ can be static, stack dynamic, or heap dynamic. Explicit deallocation using the delete operator is required for heap-dynamic objects, because C++ does not include implicit storage reclamation.


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


31. What is the root class in Objective-C?The predefined root class named NSObject


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 finalize method when the garbage collector is about to reclaim the storage occupied by the object.



Problem Set



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


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


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


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. Meanwhile, Inheritance does support it.


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


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


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

Chapter 11

Chapter 11

Review Questions

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

Chapter 10

Chapter 10


Review Questions

1. What is the definition used in this chapter for “simple” subprograms ?-Subprograms cannot be nested and all local variables are static.
2. Which of the caller of callee saves execution status information ?
-Either can save the execution status
3. What must be stored for the linkage to a subprogram ?
- Execution status information
4. What is the task of a linker ?
- find files that contain the translated subprograms referenced in that program and load them into memory, set target addresses of all calls to those subprograms in the main program to the entry addresses of those subprograms.
8. What kind of machines often use registers to pass parameters ?
- RISC Machines
10. Define static chain, static_depth, nesting_depth,and chain_offset.- static chain : a chain of static links that connect certain activation record instances in the stack.
– static depth : integer associated with a static scope that indicates how deeply it is nested in the outermost scope.
– nesting_depth : difference between static_depth of a subprogram containing reference to x and the static_depth of a subprogram containing the declaration of x.
– chain_offset : number of links to the correct activation record instance
12. How are references to variables represented in the static-chain method?It is represented by static depth.

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 particularactivation retain the value of previous activation ?
- If the variable is declared as static. Static modifier is a modifier that makes a variable history – sensitive.
7. It is stated in this chapter that when nonlocal variables are accessed in a dynamic-scoped language using the dynamic chain, variable names must be stored in the activation records with the values. If this were actually done, every nonlocal access would require a sequence of costly string comparisons on names. Design an alternative to these string comparisons that would be faster.One very simple alternative is to assign integer values to all variable names used in the program.  Then the integer values could be used in the activation records, and the comparisons would be between integer values, which are much faster than string comparisons.
8. Pascal allows gotos with nonlocal targets. How could such statements be handled if static chains were used for nonlocal variable access? 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.