Skip to content

KBP Chapter 16

This assignment is ordered by Mr. Tri Djoko Wahjono

 

 

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 ?
– a. Have a single atomic proposition on the left side
b. empty left side.

9. What does it mean for a language to be nonprocedural ?
– Language in which the programs do not exactly state how a result is to be computed but rather describe the form of the result.

Problem set
1. “All predicate calculus propositions can be algorithmically converted to clausal form”. Is this statement true or false ? Explain.
– True.

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.

KBP Chapter 15

This assignment is ordered by Mr. Tri Djoko Wahjono

 

 

Review questions
1. Define functional form, simple list, bound variable and referential transparency.
– Functional form : one that either takes one or more functions as parameters or yields a function as its result.
Simple list : A list that does not include sublist.
Bound variable : A bound variable is a variable which never changes in the expression after being bound to an actual parameter value at the time evaluation of the lambda expressions begin.
Referential transparency : A state where execution of function always produces the same result when given the same parameters.

2. What does a lambda expression specify ?
– parameters and the mapping of a function.

3. What data types were parts of the original LISP ?
– atoms and lists

4. In what common data structure are LISP lists normally stored ?
– As linked list structure in which each node has two pointers.

5. Explain why QUOTE is needed for a parameter that is a data list.
– To return lists or atoms without changing them.

6. What is a simple list ?
– A list that does not include a sublist.

7. What does the abbreviation REPL stand for ?
– Infinite Read-Evaluate-Print Loop

8. What are the three parameters to IF ?
– a predicate expression, a then expression, and else expression.

11. What are two forms of DEFINE ?
– Binds a name to value of an expression, and bind lambda expression to a name.

29. What is a curried function ?
– All functions that takes multiple parameters.

30. What does partial evaluation mean ?
– The function is evaluated with actual parameters for one or more of the leftmost formal parameters.

31. Define reader macros.
– A textual notation introduced by dispatch on one or two characters that defines special-purpose syntax

Problem set
4. Refer to a book on Haskell programming and discuss the feature of Haskell.
– Haskell features lazy evaluation, pattern matching, list comprehension, type classes, and type polymorphism. It is a purely functional language, which means that in general, functions in Haskell do not have side effects. There is a distinct construct for representing side effects, orthogonal to the type of functions. A pure function may return a side effect which is subsequently executed, modeling the impure functions of other languages.
Haskell has a strong, static type system based on Hindley–Milner type inference. Haskell’s principal innovation in this area is to add type classes, which were originally conceived as a principled way to add overloading to the language, but have since found many more uses.
The construct which represents side effects is an example of a monad. Monads are a general framework which can model different kinds of computation, including error handling, nondeterminism, parsing, and software transactional memory. Monads are defined as ordinary datatypes, but Haskell provides some syntactic sugar for their use.

9. What does the following Scheme function do ?
(define (y s list)
(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 functions do ?
(define (x lis)
(cond
((null ? lis) 0)
((not (list? (car lis)))
(cond
((eq? (car lis) #) (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.

KBP Chapter 14

This assignment is ordered by Mr. Tri Djoko Wahjono

 

Review question

1. Define exception, exception handler, raising an exception, disabling an exception, continuation, finalization, and built-in exception.

– Exception : any unusual event, erroneous or not, that is detectable by either hardware or software and that may require special processing.

Exception handler : a code unit which processes an exception.

Raising an exception : When a event associated with an exception occurs

Disabling an exception : Ignoring a certain hardware-detectable exceptions.

Continuation : Control transfer to somewhere in the program outside of the handler code or program might terminate .

Finalization : ability to complete some computation regardless of how subprogram execution terminates.

Built-in exception : Exception that is not made by the user, but rather comes as default.

 

2. When is an exception thrown or raised ?
– When an event associated with an exception occurs

 

3. What are the advantages of having support for exception handling built in to a language ?

– Without built-in exception handling, the code to detect error condition can be a clutter to the program. Existence of built-in exception handling would simplify a source program.

 

4. Give an example of hardware-detectable execution.

– Division by zero

 

5. What does it mean for an exception to be bound to an exception handler ?

– A specific exception is to be handled by a specific exception handler also, because different exceptions are to be treated differently.

 

6. What is exception propagation in Ada ?

– A powerful tool for constructing more reliable software systems.

 

8. Where does execution continue after an exception is handled in Ada ?

– Control simply continues after the exception clause.

 

10. What are the four exceptions defined in the Standard package of Ada ?

– Constraint_Error,Program_Error,Storage_Error, and Tasking_Error.

 

11. Are there any predefined exceptions in Ada ?

– Yes, there are, for example Ada.Text_IO defines the End_Error exception.

 

12. What is the use of Suppress pragma in Ada ?
– Run-time checks that are parts of built-in exceptions can be disabled in Ada programs

 

13. Describe three problems with Ada’s exception handling.

– The propagation model, which allows exceptions to be propagated to an outer scope in which the exception is not visible, inadequacy of exception handling for tasks, and exception handling was not extended to deal with new constructs in Ada 95.

 

Problem set

 

1. What mechanism did early programming languages provide to detect to attempt to deal with errors ?

– There were no possibility for the user program to detect or attempt to deal with errors. In case if error happens, the program will be terminated and control will be transferred to the operating system.

 

2. Describe the approach for the detection of subscript range errors used in C and Java.

– C does not check subscript ranges. While in Java, compilers usually generate a code to check the correctness of every subscript expression. If any exception generates, 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, for example in Ada, using an error flag parameter in all subprograms. One advantage is that the code to test the error is eliminated after every call. Such test code makes program longer and harder to read. Second advantage is that exceptions can be propagated farther in a uniform and implicit way. Also, there is an advantage that all program use a similar method to deal with exceptions, which enhances 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.

KBP Chapter 13

This assignment is ordered by Mr. Tri Djoko Wahjono

 

Review questions
1. What are the three possible levels of concurrency in programs ?
– Instruction level, Statement level, and Unit level

2. Describe the logical architecture of an SIMD computer.
– In an SIMD computer, each processor has its own local memory. One processor controls the operation of the other processors. Because all of the processors, except the controller, execute the same instruction at the same time, no synchronization is required in the software.

3. Describe the logical architecture of an MIMD computer.
-Each processor in an MIMD computer executes its own instruction stream. MIMD computers can appear in two distinct configurations: distributed and shared memory systems. The distributed MIMD machines, in which each processor has its own memory, can be either built in a single chassis or distributed, perhaps over a large area. The shared-memory MIMD machines obviously must provide some means of synchronization to
prevent memory access clashes.

4. What level of program concurrency is best supported by SIMD computers ?
-Instruction concurrency level

5. What level of program concurrency is best supported by MIMD computers ?
-Unit concurrency level.

6. Describe the logical architecture of a vector processor.
– Vector processor have groups of registers that store the operands of a vector operation in which
the same instruction is executed on the whole group of operands simultaneously.

7. What is the difference between physical and logical concurrency ?
– Physical concurrency is when it is assumed that if more than one processor is available, several program units from the same program literally execute simultaneously. Logical concurrency is assuming multiple processors can execute simultaneously while the actual execution is taking place in a single processor.

8. What is the work of a scheduler ?
– Managing the share of processors among tasks.

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

10. When is a task in a blocked state ?
– When its execution is interrupted by one of several different events

11. Give three characteristics of thread that distinguish them from subprograms
– A task may be implicitly started, whereas a subprogram must be explicitly called.
– When a program unit invokes a task, in some cases it need not wait for the task to complete execution before continuing its own.
– When execution of task is completed, control may or may not return to the unit that started that execution

12. What is a heavyweight task ? What is a lightweight task ?
– Heavyweight task is a task that executes in its own address space. Lightweight tasks are tasks run in the same address space.

13. Define task ,synchronization, competition and cooperation synchronization, liveness ,race condition and deadlock.
– Task : unit of a program, similar to a subprogram that can be in concurrent execution with other units of same program
Synchronization : a mechanism that controls the order in which task execute.
Competition Synchronization : Synchronization between two task when both require a single resource that can’t be used together.
Cooperation Synchronization : Synchronization in which a task must wait for other task to finish before it can begin or continue its execution
Liveness : condition if some event, like program completion is supposed to occur, it will occur eventually. That is, progress is actually made.
Race Condition : When two or more tasks are racing to use the shared resource and the behavior of the program depends on which task arrives first.
Deadlock : a condition when a program is trapped inside an endless loop due to error between task synchronization.

14. What kind of tasks do not require any kind of synchronization ?
-Tasks that are not depending on the outcome or output from other tasks.

15. Describe the five different states a task can be.
– New = A task is in the new state when it has been created but yet to start its execution
– Ready = A task that is ready to run but is not currently running. Either it has not been run yet or it had run previously but got blocked.
– Running = A task that is currently being executed.
– Blocked = a task that has been running ,but the execution was interrupted by an event.
– Dead = A task that is no longer active in any sense, either when the execution is completed or killed by the program

16. What is task descriptor ?
– A data structure that stores all of the relevant information about the execution state of a task.

17. In the context of language support for concurrency, what is a guard ?
– Linguistic device that allows the guarded code to be executed only when a specified condition is true.

Problem set

1. Explain clearly why a race condition can create problems for a system .
– A race condition allows different outputs to come out of the synchronization, as stated in the book, for example task A which increments an integer and task B that multiplies an integer with 2.
Say we have integer A with value of 3. If both tasks are run in race condition, its value could be either 7 (when B runs and finishes before A starts) or 8 (vice versa) or, either 4 or 6 (if they started at the same time, 4 when A finishes later and 6 when B finishes the last. ). Without proper synchronization on timing, the output can vary. Thus this makes the program unreliable.

2. What are the different ways to handle deadlock ?
– One of the ways is to design algorithm where tasks that can cause deadlock to not to run together. Or, to allow them to execute at the same time but with an exception if a deadlock happens, the program will either reset its status to the time when deadlock has not occurred or to break forcefully from the loop and continues execution.

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 ?
– A continuous check might mean a deadlock for a task, where it does something that does not has a direct impact on the program unless the specified event happens. It does consume extra processor capability. A better way to do this might be executing the same task when an event occurs, instead of running it first and make it waiting and continuously wasting CPU capability.

KBP Chapter 12

This assignment is ordered by Mr. Tri Djoko Wahjono

 

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.

8. What is an abstract method ? What is an abstract class ?
– a method which all descendant classes should have. An abstract class is a class which has abstract method.

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

11. What is the message protocol of an object ?
– Colletions of an object’s methods.

12. From where are Smalltalk objects allocated ?
– From the heap

38. What is Boxing ?
– Coercion of primitive values when they are put in object context

52. Does Ruby support multiple inheritance ?
– No. it does not

 

Problem Set

2. In what ways can “compatible “ be defined for the relationship between an overridden method and the overriding method ?
– in ways of its formal definition, the parameters and return types.

3. Compare the inheritance of C++ and Java.
– In Java, all objects are Inherited, either directly or indirectly. While in C++ a class can be defined to stand on its own without an ancestor.

– In Java, there’s no access level specifier of inheritance, while C++ has private public and protected.

– In Java, the functions are virtual by default. While in C++ the functions CAN BE MADE virtual with the keyword virtual

7. What is one programming situation where multiple inheritance has a significant disadvantage over interfaces ?
– When two or more parent classes are derived from one grandparent class and has one child. (diamond problem)

9. Given an example of inheritance in C++, where a subclass overrides the superclass methods.
– class human{
public :
void eat(){std::cout<<”Eating”;}
}
class man : public human{
public :
void eat(){std::cout<<”Eat like a boss”;}
}

10. Explain one advantage of inheritance
– Allows programmer to reuse a class with modifications that doesn’t apply to the initial class, so both class can still be used. This also improves readability and writability.

14. Explain type checking in Java
-Type checking happens before execution. Type checking can only uses type information that have declared in your program, and not the possible type that an object has at runtime. Java checks all line of code to make sure that it uses values correctly according to the declared types.

16. State why Java is said to be more pure object oriented than C++.
-Because Java implements pure class. Every function / statements in Java is run by a class. While in C++ not all functions are run by a class.

17. What are the different options for object destruction in Java ?
– Using Close method or Finalize method.

KBP Chapter 11

This assignment is ordered by Mr. Tri Djoko Wahjono

 

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.

3. What are the advantages of the two parts of the definition of abstract data type ?

– Increased reliability, Reduces range of code and number of variables which a programmer must be aware when writing / reading part of program. Make name conflict less likely to happen

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 ?

– To eliminate 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 ?

– Class must be accessed from an instance of itself while package can be accessed directly.

15. What is the purpose of a C++ destructor ?

– To deallocate heap space the object used.

 

16. What are the legal return types of a destructor ?

– destructor has no return type

 

21. What are initializers in Objective-C?

– Constructors that must be explicitly called.

 

26. Why does Java not have destructors ?

– Because Java has its own implicit garbage collection.

 

Problem Set

 

2. Suppose someone designed a stack abstract data type in which the function top returned an access path (or pointer ) rather than returning a copy of the top element. This is not a true data abstraction. Why ? Give an example that illustrates the problem.

– The problem with this is that the user is given access to the stack through the returned value of the “top” function. For example, if p is a pointer to objects of the type stored in the stack, we could have:

p = top(stack1);

*p = 42;

These statements access the stack directly, which violates the principle of a data abstraction.

4. What are the advantages of the nonpointer concept in Java ?

– Variable Access are absolutely defined by the programmer

– No memory leak (i.e. dangling pointers, nameless variables etc)

9. What happens if the constructor is absent in Java and C++ ?
– The compiler will automatically make a default one

11. Why is the destructor of C# rarely used ?
– Because C# has its own garbage collection method , just like Java

KBP Chapter 10

This assignment is ordered by Mr. Tri Djoko Wahjono

 

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

1. Show the stack with all activation record instances, including static and dynamic chains, when execution reaches position 1 in the following skeletal program. Assume Bigsub is at level 1.

(page 487)

      -      +--------------------------------------------+ <------ top
     /       !       Dynamic link                     ! --+>----\
    /        !----------------------------------------+---!     !
   B         !       Static link                      ! -----\  !
    \        !----------------------------------------+---!  !  !
     \       !       Return (to C)                    !   !  !  !
      -      !----------------------------------------+---!<-+--/
     /       !       Dynamic link                     ! --+>-!
    /        !----------------------------------------+---!  !
   C         !       Static link                      ! --+>-!
    \        !----------------------------------------+---!  !
     \       !       Return (to A)                    !   !  !
      -      !----------------------------------------+---!<-/
     /       !       Dynamic link                     ! --+>------\
    /        !----------------------------------------+---!       !
   A         !       Static link                      ! --+>------!
    \        !----------------------------------------+---!       !
     \       !       Return (to BIGSUB)               !   !       !
      -      !----------------------------------------+---!<------/
BIGSUB       !       Local variables                  !   !
             +----------------------------------------+---+

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

– Using approach that uses an auxiliary data structure called a display. Or, to write variable names as integers. These integers act like an array. So when the activation happens, the comparisons will be faster.

 

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.