Logic, Functional, and Object-Oriented Programming Concepts

Chapter 16: Logic Programming

  1. What are the three primary uses of symbolic logic in formal logic?
    Express propositions, express relationships, and infer conclusions.

  2. What are the two parts of a compound term?
    Functor and arguments.

  3. What are the two modes in which a proposition can be stated?
    Fact or rule.

  4. What is the general form of a proposition in clausal form?
    Head :- Body.

  5. What are antecedents? Consequences?
    Antecedents: Conditions (Body).
    Consequences: Results (Head).

  6. Give general (not rigorous) definitions of resolution and unification.

    • Resolution: Infers new facts from existing ones.

    • Unification: Matches terms by finding a substitution.

  7. What are the forms of Horn clauses?
    Facts, rules, and queries.

  8. What is the basic concept of declarative semantics?
    Logic specifies what to do, not how to do it.

  9. What does it mean for a language to be nonprocedural?
    It specifies results without defining execution steps.

  10. What are the three forms of a Prolog term?
    Constants, variables, and structures.

  11. What is an uninstantiated variable?
    A variable without a value.

  12. What are the syntactic forms and usage of fact and rule statements in Prolog?

    • Fact: predicate(arguments).

    • Rule: head :- body.

  13. What is a conjunction?
    A sequence of goals joined by ,.

  14. Explain the two approaches to matching goals to facts in a database.
    Unification and pattern matching.

  15. Explain the difference between a depth-first and a breadth-first search when discussing how multiple goals are satisfied.

    • Depth-first: Explores one branch fully before backtracking.

    • Breadth-first: Explores all branches at each level.

  16. Explain how backtracking works in Prolog.
    When a goal fails, Prolog backtracks to try alternative solutions.

  17. Explain what is wrong with the Prolog statement K is K + 1.
    Variables cannot be reassigned; K must already have a value.

  18. What are the two ways a Prolog programmer can control the order of pattern matching during resolution?
    Ordering clauses and using the cut operator.

  19. Explain the generate-and-test programming strategy in Prolog.
    Generate potential solutions and test their validity.

  20. Explain the closed-world assumption used by Prolog. Why is this a limitation?
    Assumes any statement not known to be true is false, limiting incomplete data handling.

  21. Explain the negation problem with Prolog. Why is this a limitation?
    Negation assumes closed-world assumption, leading to incorrect results with incomplete information.

  22. Explain the connection between automatic theorem proving and Prolog’s inferencing process.
    Both rely on resolution and unification.

  23. Explain the difference between procedural and nonprocedural languages.
    Procedural defines how tasks are performed; nonprocedural specifies what tasks are performed.

  24. Explain why Prolog systems must do backtracking.
    To explore alternative solutions when goals fail.

  25. What is the relationship between resolution and unification in Prolog?
    Resolution uses unification to infer new facts.


Chapter 15: Functional Programming

  1. Define functional form, simple list, bound variable, and referential transparency.

    • Functional form: A higher-order function.

    • Simple list: A list of elements, all of the same type.

    • Bound variable: A variable tied to a specific scope.

    • Referential transparency: Expressions yield the same result in any context.

  2. What does a lambda expression specify?
    An anonymous 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?
    Linked lists.

  5. Explain why QUOTE is needed for a parameter that is a data list.
    To prevent evaluation of the list as a function.

  6. What is a simple list?
    A list containing only atomic elements.

  7. What does the abbreviation REPL stand for?
    Read-Eval-Print Loop.

  8. What are the three parameters to IF?
    Condition, true branch, false branch.

  9. What are the differences between =, EQ?, EQV?, and EQUAL?

    • =: Numeric equality.

    • EQ?: Checks object identity.

    • EQV?: Checks equivalence of primitive values.

    • EQUAL: Deep structural equality.

  10. What are the differences between the evaluation method used for the Scheme special form DEFINE and that used for its primitive functions?
    DEFINE evaluates lazily, while primitives evaluate eagerly.

  11. What are the two forms of DEFINE?
    Define variables and define functions.

  12. Describe the syntax and semantics of COND.
    A multi-way conditional in Scheme. Syntax: (COND (condition1 result1) … (else result)).

  13. Why are CAR and CDR so named?
    From the IBM 704: “Contents of Address Register” and “Contents of Decrement Register.”

  14. If CONS is called with two atoms, say ‘A and ‘B, what is returned?
    A pair: (A . B).

  15. Describe the syntax and semantics of LET in Scheme.
    Binds variables to values in a local scope: (LET ((var1 val1) …) body).

  16. What are the differences between CONS, LIST, and APPEND?

    • CONS: Adds an element to a list.

    • LIST: Creates a new list.

    • APPEND: Combines lists.

  17. Describe the syntax and semantics of mapcar in Scheme.
    Applies a function to each element of a list: (MAPCAR function list).

  18. What is tail recursion? Why is it important to define functions that use recursion to specify repetition to be tail recursive?
    Tail recursion occurs when the recursive call is the last action in a function. It improves efficiency by avoiding additional stack frames.

  19. Why were imperative features added to most dialects of Lisp?
    To increase flexibility and usability.

  20. In what ways are Common Lisp and Scheme opposites?
    Common Lisp emphasizes features and libraries, while Scheme emphasizes simplicity.

  21. What scoping rule is used in Scheme? In Common Lisp? In ML? In Haskell? In F#?
    Scheme and ML use lexical scoping; Common Lisp supports dynamic scoping; Haskell and F# use lexical scoping.

  22. What happens during the reader phase of a Common Lisp language processor?
    Translates code into internal data structures.


Chapter 15: continued

  1. What are two ways that ML is fundamentally different from Scheme?
    Stronger type system and pattern matching.

  2. What is stored in an ML evaluation environment?
    Variable bindings and function definitions.

  3. What is the difference between an ML val statement and an assignment statement in C?
    val binds values immutably, whereas C assignments can reassign values.

  4. What is type inferencing, as used in ML?
    The compiler automatically deduces the types of expressions.

  5. What is the use of the fn reserved word in ML?
    Introduces an anonymous function.

  6. Can ML functions that deal with scalar numerics be generic?
    Yes, through parametric polymorphism.

  7. What is a curried function?
    A function that takes multiple arguments one at a time.

  8. What does partial evaluation mean?
    Evaluating a function with some arguments, creating a specialized function.

  9. Describe the actions of the ML filter function.
    Returns a list containing only elements that satisfy a predicate.

  10. What operator does ML use for Scheme’s CAR?
    hd.

  11. What operator does ML use for functional composition?
    o.

  12. What is a strict programming language?
    Evaluates function arguments before applying the function.

  13. What programming paradigms are supported by F#?
    Functional, imperative, and object-oriented.

  14. With what other programming languages can F# interoperate?
    .NET languages like C# and VB.NET.

  15. What does F#’s let do?
    Defines variables or functions.

  16. How is the scope of a F# let construct terminated?
    By indentation or the in keyword.

  17. What is the underlying difference between a sequence and a list in F#?
    Sequences are lazy; lists are eager.

  18. What is the difference between the let of ML and that of F#, in terms of extent?
    F#’s let can be recursive.

  19. What is the syntax of a lambda expression in F#?
    (fun x -> expression).

  20. Does F# coerce numeric values in expressions? Argue in support of the design choice.
    No, to maintain type safety.

  21. What support does Python provide for functional programming?
    Functions like map, filter, and comprehensions.

  22. What function in Ruby is used to create a curried function?
    Proc#curry.

  23. Is the use of functional programming expanding or shrinking?
    Expanding, due to increased interest in parallelism and immutability.

  24. What is one characteristic of functional programming languages that makes their semantics simpler than that of imperative languages?
    Referential transparency.

  25. What is the flaw in using lines of code to compare the productivity of functional languages and that of imperative languages?
    Functional languages require fewer lines, which can distort comparisons.

Why can concurrency be easier with functional languages than imperative languages?
Immutability eliminates data races


Chapter 12: Object-Oriented Programming

  1. Describe the three characteristic features of object-oriented languages.
    Encapsulation, inheritance, and polymorphism.

  2. What is the difference between a class variable and an instance variable?
    Class variables are shared among all instances; instance variables are unique to each object.

  3. What is multiple inheritance?
    A class inheriting from more than one parent class.

  4. What is a polymorphic variable?
    A variable that can hold values of different types during execution.

  5. What is an overriding method?
    A method in a subclass that redefines a method in its superclass.

  6. Describe a situation where dynamic binding is a great advantage over static binding.
    When implementing polymorphic behavior, such as in frameworks where the specific type is unknown at compile time.

  7. What is a virtual method?
    A method defined to be dynamically bound.

  8. What is an abstract method? What is an abstract class?
    An abstract method has no implementation. An abstract class cannot be instantiated and may contain abstract methods.

  9. Describe briefly the seven design issues used in this chapter for object-oriented languages.
    Encapsulation, inheritance, polymorphism, access control, method binding, multiple inheritance, and object creation/destruction.

  10. What is a nesting class?
    A class defined within another class.

  11. What is the message protocol of an object?
    The set of methods that can be called on the object.

  12. From where are Smalltalk objects allocated?
    The heap.

  13. Explain how Smalltalk messages are bound to methods. When does this take place?
    Dynamically at runtime.

  14. What type checking is done in Smalltalk? When does it take place?
    None at compile-time; all type checking is done at runtime.

  15. What kind of inheritance, single or multiple, does Smalltalk support?
    Single inheritance.

  16. What are the two most important effects that Smalltalk has had on computing?
    Popularized object-oriented programming and graphical user interfaces.

  17. In essence, all Smalltalk variables are of a single type. What is that type?
    Object.

  18. From where can C++ objects be allocated?
    Stack, heap, or static memory.

  19. How are C++ heap-allocated objects deallocated?
    Using the delete operator.

  20. Are all C++ subclasses subtypes? If so, explain. If not, why not?
    No, only if they satisfy the Liskov Substitution Principle.

  21. Under what circumstances is a C++ method call statically bound to a method?
    When the method is not declared as virtual.

  22. What drawback is there to allowing designers to specify which methods can be statically bound?
    Potential for runtime errors when dynamic behavior is needed.

  23. What are the differences between private and public derivations in C++?
    Private derivation restricts inherited members to private access, while public derivation retains access levels.

  24. What is a friend function in C++?
    A function granted special access to private members of a class.

What is a pure virtual function in C++?
A function with no implementation that must be overridden in derived classes.


  1. Chapter 12 continued
  2. How are parameters sent to a superclass’s constructor in C++?
    Using an initializer list in the subclass constructor.

  3. What is the single most important practical difference between Smalltalk and C++?
    Smalltalk is fully dynamic; C++ is statically typed.

  4. How is the type system of Java different from that of C++?
    Java uses runtime type checking; C++ has static type checking.

  5. From where can Java objects be allocated?
    The heap.

  6. What is boxing?
    Converting a primitive type to its corresponding object wrapper.

  7. How are Java objects deallocated?
    By the garbage collector.

  8. Are all Java subclasses subtypes?
    Yes, because Java enforces the Liskov Substitution Principle.

  9. How are superclass constructors called in Java?
    Using super.

  10. Under what circumstances is a Java method call statically bound to a method?
    When the method is declared as final or static.

  11. In what way do overriding methods in C# syntactically differ from their counterparts in C++?
    C# uses the override keyword explicitly.

  12. How can the parent version of an inherited method that is overridden in a subclass be called in that subclass in C#?
    Using base.methodName().

  13. How does Ruby implement primitive types, such as those for integer and floating-point data?
    As objects.

  14. How are getter methods defined in a Ruby class?
    Using attr_reader.

  15. What access controls does Ruby support for instance variables?
    Private access by default.

  16. What access controls does Ruby support for methods?
    Public, private, and protected.

  17. Are all Ruby subclasses subtypes?
    No, Ruby does not enforce the Liskov Substitution Principle.

  18. Does Ruby support multiple inheritance?
    No, but it supports mixins using modules.

  19. What does reflection allow a program to do?
    Inspect or modify its structure and behavior at runtime.

  20. In the context of reflection, what is metadata?
    Information about the program’s structure, such as class and method definitions.

  21. What is introspection?
    The ability of a program to examine its structure at runtime.

  22. What is intercession?
    The ability of a program to modify its structure at runtime.

  23. What class in Java stores information about classes in a program?
    Class.

  24. For what is the Java name extension .class used?
    For storing compiled bytecode.

  25. What does the Java getMethods method do?
    Retrieves information about the methods of a class.

For what is the C# namespace System.Reflection.Emit used?
For generating and working with Intermediate Language (IL) code


Chapter 11: Abstract Data Types

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

  2. Define abstract data type.
    A data type defined by its behavior (operations) rather than its implementation.

  3. What are the advantages of the two parts of the definition of abstract data type?
    Encapsulation (hides implementation details) and modularity (enables reuse and maintenance).

  4. What are the language design requirements for a language that supports abstract data types?
    Syntax for defining ADTs, access control, and encapsulation mechanisms.

  5. What are the language design issues for abstract data types?
    Access control, type-checking mechanisms, and parameterized types.

  6. From where are C++ objects allocated?
    Stack, heap, or static memory.

  7. In what different places can the definition of a C++ member function appear?
    Inside the class definition (inline) or outside using the scope resolution operator.

  8. What is the purpose of a C++ constructor?
    To initialize an object’s data members.

  9. What are the legal return types of a constructor?
    Constructors do not have a return type.

  10. Where are all Java methods defined?
    Inside a class.

  11. How are C++ class instances created?
    On the stack (automatic) or the heap (dynamic).

  12. From where are Java class instances allocated?
    The heap.

  13. Why does Java not have destructors?
    Java uses garbage collection to manage memory.

  14. Where are all Java methods defined?
    Inside classes.

  15. Where are Java classes allocated?
    In the heap.

  16. Why are destructors not as frequently needed in Java as they are in C++?
    Automatic garbage collection.

  17. What is a friend function? What is a friend class?
    A function or class with special access to private/protected members of another class.

  18. What is one reason Java does not have friend functions or friend classes?
    To enforce stricter encapsulation and avoid access abuse.

  19. Describe the fundamental differences between C# structs and its classes.
    Structs are value types, while classes are reference types.

  20. How is a struct object in C# created?
    On the stack, unless explicitly boxed.

  21. Explain the three reasons accessors to private types are better than making the types public.
    Maintains encapsulation, provides validation, and supports future changes without breaking the interface.

  22. What are the differences between a C++ struct and a C# struct?
    C++ structs are similar to classes, while C# structs are value types with limited features.

  23. What is the name of all Ruby constructors?
    initialize.

  24. What is the fundamental difference between the classes of Ruby and those of C++ and Java?
    Ruby classes are dynamic and open, allowing modification at runtime.

  25. How are instances of C++ template classes created?
    By specifying a type during instantiation.

  26. Describe the two problems that appear in the construction of large programs that led to the development of encapsulation constructs.
    Name conflicts and lack of modularity.

  27. What problems can occur using C to define abstract data types?
    Lack of access control and encapsulation.

  28. What is a C++ namespace, and what is its purpose?
    A container for identifiers to prevent naming conflicts.

  29. What is a Java package, and what is its purpose?
    A grouping mechanism for related classes to provide modularity and avoid naming conflicts.

  30. Describe a .NET assembly.
    A compiled code library for deployment and versioning in .NET.

What elements can appear in a Ruby module?
Methods, constants, and nested modules.


Chapter 9: Subprograms

  1. What are the three general characteristics of subprograms?
    Single entry point, caller suspends execution during the subprogram’s execution, and control returns to the caller upon completion.

  2. What does it mean for a subprogram to be active?
    A subprogram is active when its execution has begun but not yet completed.

  3. What is given in the header of a subprogram?
    Its name, parameters, and possibly the return type.

  4. What characteristic of Python subprograms sets them apart from those of other languages?
    They can have default parameter values and support keyword arguments.

  5. What languages allow a variable number of parameters?
    C, C++, Python, Ruby, and JavaScript.

  6. What is a Ruby array formal parameter?
    A parameter that captures a variable number of arguments into an array.

  7. What is a parameter profile? What is a subprogram protocol?
    Parameter profile: The number, order, and types of a subprogram’s parameters.
    Subprogram protocol: The parameter profile and return type.

  8. What are formal parameters? What are actual parameters?
    Formal parameters: Defined in the subprogram.
    Actual parameters: Passed by the caller during invocation.

  9. What are the advantages and disadvantages of keyword parameters?
    Advantages: Improved readability and flexibility.
    Disadvantages: Increased verbosity and potential for errors if mismatched.

  10. What are the differences between a function and a procedure?
    Functions return a value; procedures do not.

  11. What are the design issues for subprograms?
    Parameter passing, local variables, recursion, and nesting.

  12. What are the advantages and disadvantages of dynamic local variables?
    Advantages: Flexibility and memory efficiency.
    Disadvantages: Overhead in allocation/deallocation and potential side effects.

  13. What are the advantages and disadvantages of static local variables?
    Advantages: Faster access and persistence between calls.
    Disadvantages: Lack of flexibility and potential memory wastage.

  14. What languages allow subprogram definitions to be nested?
    Ada, Python, and JavaScript.

  15. What are the three semantics models of parameter passing?
    Pass-by-value, pass-by-result, and pass-by-reference.

  16. What are the modes, the conceptual models of transfer, the advantages, and the disadvantages of pass-by-value, pass-by-result, pass-by-value-result, and pass-by-reference parameter-passing methods?

    • Pass-by-value: Copies data; safer but slower for large data.

    • Pass-by-result: Assigns back the final value; can cause side effects.

    • Pass-by-value-result: Combines the two; more overhead.

    • Pass-by-reference: Directly accesses memory; faster but less safe.

  17. Describe the ways that aliases can occur with pass-by-reference parameters.
    Aliases can occur when multiple parameters reference the same memory location.

  18. What is the difference between the way original C and C89 deal with an actual parameter whose type is not identical to that of the corresponding formal parameter?
    Original C performs implicit conversions; C89 requires stricter type checking.

  19. What are two fundamental design considerations for parameter-passing methods?
    Efficiency and safety.

  20. Describe the problem of passing multidimensioned arrays as parameters.
    Dimensions must be explicitly declared or passed, complicating syntax and implementation.

  21. What is the name of the parameter-passing method used in Ruby?
    Pass-by-reference-value.

  22. What are the two issues that arise when subprogram names are parameters?
    Binding the subprogram name and its referencing environment.

  23. Define shallow and deep binding for referencing environments of subprograms that have been passed as parameters.

    • Shallow binding: Uses the caller’s environment.

    • Deep binding: Uses the environment where the subprogram was defined


Chapter 9: 

  1. What is an overloaded subprogram?
    A subprogram with the same name but different parameter profiles.

  2. What is parametric polymorphism?
    The ability to write subprograms that can operate on any data type.

  3. What causes a C++ template function to be instantiated?
    Calling the function with a specific data type.

  4. In what fundamental ways do the generic parameters to a Java 5.0 generic method differ from those of C++ methods?
    Java performs type erasure; C++ generates separate code for each type.

  5. If a Java 5.0 method returns a generic type, what type of object is actually returned?
    The object type is erased to its bound or Object.

  6. If a Java 5.0 generic method is called with three different generic parameters, how many versions of the method will be generated by the compiler?
    One, due to type erasure.

  7. What are the design issues for functions?
    Return types, recursion, and parameter handling.

  8. Name two languages that allow multiple values to be returned from a function.
    Python and Ruby.

  9. What exactly is a delegate?
    A reference to a method, commonly used in C# for callbacks.

  10. What is the main drawback of generic functions in F#?
    Lack of runtime type information.

  11. What is a closure?
    A function with an associated referencing environment.

  12. What are the language characteristics that make closures useful?
    First-class functions and lexical scoping.

  13. What languages allow the user to overload operators?
    C++, Python, and Ruby.

In what ways are coroutines different from conventional subprograms?
Coroutines allow multiple entry points and can yield control back to the caller

Chapter 8 stuff

  1. What is the difference between the for statement of C++ and that of Java?
    Java’s for includes enhanced syntax for iterating over collections (for-each).

  2. In what way is C’s for statement more flexible than that of many other languages?
    All three components (initialization, condition, update) are optional and can be arbitrary expressions.

  3. What does the range function in Python do?
    Generates a sequence of numbers within a specified range.

  4. What contemporary languages do not include a goto?
    Python, Java, and modern functional languages.

  5. What are the design issues for logically controlled loop statements?
    Syntax, condition evaluation, and exit mechanisms.

  6. What is the main reason user-located loop control statements were invented?
    To provide greater control over loop termination or continuation.

  7. What are the design issues for user-located loop control mechanisms?
    Readability, flexibility, and effect on nested loops.

  8. What advantage does Java’s break statement have over C’s break statement?
    Java’s break can specify a labeled loop to exit, improving control in nested loops.

  9. What are the differences between the break statement of C++ and that of Java?
    Java allows labeled breaks; C++ does not.

  10. What is a user-defined iteration control?
    Using constructs like iterators or higher-order functions to define iteration behavior.

  11. What Scheme function implements a multiple selection statement?
    COND.

  12. How does a functional language implement repetition?
    Through recursion.

  13. How are iterators implemented in Ruby?
    With blocks and methods like each.

  14. What language predefines iterators that can be explicitly called to iterate over its predefined data structures?
    Python.

What common programming language borrows part of its design from Dijkstra’s guarded commands?
Ada.


Chapter 8: Control Structures

  1. What is the definition of control structure?
    A mechanism that controls the flow of execution in a program (e.g., sequence, selection, iteration).

  2. What did Böhm and Jacopini prove about flowcharts?
    All algorithms can be implemented using only three control structures: sequence, selection, and iteration.

  3. What is the definition of block?
    A sequence of statements treated as a single unit of execution.

  4. What is/are the design issue(s) for all selection and iteration control statements?
    Number of branches, syntax, type checking, and nesting rules.

  5. What are the design issues for selection structures?
    Form of expression, multiple branches, and rules for nesting.

  6. What is unusual about Python’s design of compound statements?
    Python uses indentation instead of braces or delimiters to define compound statements.

  7. Under what circumstances must an F# selector have an else clause?
    All expressions in F# must return a value, so an else clause is required.

  8. What are the common solutions to the nesting problem for two-way selectors?
    Using keywords like endif or restructuring code with explicit blocks.

  9. What are the design issues for multiple-selection statements?
    Evaluation method for conditions, execution of multiple segments, and readability.

  10. Between what two language characteristics is a trade-off made when deciding whether more than one selectable segment is executed in one execution of a multiple selection statement?
    Readability and flexibility.

  11. What is unusual about C’s multiple-selection statement?
    The switch statement allows fall-through between cases unless explicitly prevented with a break.

  12. On what previous language was C’s switch statement based?
    ALGOL W.

  13. Explain how C#’s switch statement is safer than that of C.
    C# does not allow implicit fall-through between case labels without an explicit goto.

  14. What are the design issues for all iterative control statements?
    Type of iteration (pretest, posttest, or midtest) and control mechanisms.

  15. What are the design issues for counter-controlled loop statements?
    Initialization, termination conditions, and scope of the counter variable.

What is a pretest loop statement? What is a posttest loop statement?
Pretest: Tests the condition before execution (e.g., while).
Posttest: Executes once before testing (e.g., do-while).

Problem 3. Rewrite the following code segment using a multiple-selection statement in various languages.

c

Copy code

if ((k == 1) || (k == 2)) j = 2 * k – 1;

if ((k == 3) || (k == 5)) j = 3 * k + 1;

if (k == 4) j = 4 * k – 1;

if ((k == 6) || (k == 7) || (k == 8)) j = k – 2;

2. In Python

python

Copy code

match k:

    case 1 | 2:

        j = 2 * k – 1

    case 3 | 5:

        j = 3 * k + 1

    case 4:

        j = 4 * k – 1

    case 6 | 7 | 8:

        j = k – 2

    case _:

        pass



Problem 19. Using Prolog structures parent, male, and female, define mother.

prolog

Copy code

mother(X, Y) :- parent(X, Y), female(X).

Problem 20. Define sister using Prolog structures.

prolog

Copy code

sister(X, Y) :- parent(Z, X), parent(Z, Y), female(X), X \= Y.

Problem 21. Write a Prolog program that finds the maximum of a list of numbers.

prolog

Copy code

max_list([X], X).

max_list([X|Xs], Max) :-

    max_list(Xs, TailMax),

    Max is max(X, TailMax).

Problem 22. Write a Prolog program that succeeds if the intersection of two lists is empty.

prolog

Copy code

intersection_empty([], _).

intersection_empty([X|Xs], Ys) :-

    \+ member(X, Ys),

    intersection_empty(Xs, Ys).

Problem 23. Write a Prolog program that returns the union of two lists.

prolog

Copy code

union([], Ys, Ys).

union([X|Xs], Ys, Zs) :-

    member(X, Ys), !,

    union(Xs, Ys, Zs).

union([X|Xs], Ys, [X|Zs]) :-

    union(Xs, Ys, Zs).

Problem 24. Write a Prolog program that returns the final element of a list.

prolog

Copy code

last_element([X], X).

last_element([_|Xs], Y) :-

    last_element(Xs, Y).

Problem 25. Write a Prolog program that implements quicksort.

prolog

Copy code

quicksort([], []).

quicksort([X|Xs], Sorted) :-

    partition(X, Xs, Smaller, Greater),

    quicksort(Smaller, SortedSmaller),

    quicksort(Greater, SortedGreater),

    append(SortedSmaller, [X|SortedGreater], Sorted).

partition(_, [], [], []).

partition(Pivot, [X|Xs], [X|Smaller], Greater) :-

    X =

    partition(Pivot, Xs, Smaller, Greater).

partition(Pivot, [X|Xs], Smaller, [X|Greater]) :-

    X > Pivot,

    partition(Pivot, Xs, Smaller, Greater).


Problem 10. Write a Scheme function that computes the volume of a sphere, given its radius.

scheme

Copy code

(define (sphere-volume r)

  (* (/ 4 3) 3.14159 (expt r 3)))

Problem 11. Write a Scheme function that computes the real roots of a quadratic equation.

Using IF Function:

scheme

Copy code

(define (quadratic-roots a b c)

  (let ((discriminant (- (* b b) (* 4 a c))))

    (if (

        (display “The roots are complex.”)

        (list (/ (+ (- b) (sqrt discriminant)) (* 2 a))

              (/ (- (- b) (sqrt discriminant)) (* 2 a))))))

Problem 12. Repeat Problem 11 using COND Function.

scheme

Copy code

(define (quadratic-roots-cond a b c)

  (let ((discriminant (- (* b b) (* 4 a c))))

    (cond ((

          (else (list (/ (+ (- b) (sqrt discriminant)) (* 2 a))

                      (/ (- (- b) (sqrt discriminant)) (* 2 a)))))))

Problem 13. Write a Scheme function that raises A to the B power.

scheme

Copy code

(define (power a b)

  (if (= b 0)

      1

      (* a (power a (- b 1)))))

Problem 14. Write a Scheme function that returns the number of zeros in a given simple list.

scheme

Copy code

(define (count-zeros lst)

  (cond ((null? lst) 0)

        ((= (car lst) 0) (+ 1 (count-zeros (cdr lst))))

        (else (count-zeros (cdr lst)))))

Problem 15. Write a Scheme function that returns a list of the largest and smallest numbers.

scheme

Copy code

(define (min-max lst)

  (let loop ((lst lst) (min (car lst)) (max (car lst)))

    (if (null? lst)

        (list min max)

        (loop (cdr lst) (min min (car lst)) (max max (car lst))))))

Problem 16. Write a Scheme function that removes all top-level instances of a given atom from a list.

scheme

Copy code

(define (remove-atom lst atom)

  (cond ((null? lst) ‘())

        ((eq? (car lst) atom) (remove-atom (cdr lst) atom))

        (else (cons (car lst) (remove-atom (cdr lst) atom)))))


1. Key Differences

AspectSchemePrologLisp
ParadigmFunctional programmingLogic programmingFunctional programming
Execution ModelExpression evaluation, recursion-centricResolution and unification for goal satisfactionExpression evaluation, recursion-centric
SyntaxMinimalistic and clean ((operator operand operand))Rule-based with facts, rules, and queriesParentheses-heavy ((operator operand operand))
TypingDynamically typedDynamically typedDynamically typed
Use of VariablesLexically scoped and immutableLogical variables; single-assignmentLexically scoped and mutable
Primary Data TypesLists, symbols, numbersFacts, rules, queriesLists, symbols, numbers
Evaluation OrderEager evaluationBacktracking with depth-first searchEager evaluation
Primary Use CaseFunctional programming and teachingKnowledge representation and AIGeneral-purpose functional programming

2. Special Features

Scheme

  • Minimalism: Designed with simplicity in mind, Scheme is a streamlined variant of Lisp.
  • First-Class Functions: Functions are first-class citizens, meaning they can be passed as arguments or returned as values.
  • Tail-Call Optimization: Supports efficient recursion by reusing stack frames for tail-recursive calls.
  • Continuations: Supports advanced control structures through call/cc (call with current continuation).
  • Hygienic Macros: Ensures that macros do not inadvertently clash with variable names in the calling code.

Prolog

  • Declarative Nature: Focuses on what the program should achieve rather than how it should achieve it.
  • Logic-Based: Uses facts, rules, and queries to infer relationships through logical reasoning.
  • Backtracking: Automatically searches for all possible solutions to a query using depth-first search.
  • Pattern Matching: Matches terms to unify variables with values.
  • No Control Flow Needed: The logic engine handles control flow implicitly based on rules and facts.

Lisp

  • Parent Language: Lisp is the ancestor of many functional languages, including Scheme.
  • Code-as-Data: Uses a uniform syntax for both code and data (homoiconicity), enabling powerful metaprogramming.
  • Dynamic Typing: Variables and expressions can hold values of any type at runtime.
  • Rich Ecosystem: Features many dialects, including Common Lisp and Emacs Lisp, each with unique libraries.
  • Macros: Extremely powerful macros allow transformation and generation of code at compile time.

3. Similarities

  • Parentage: Scheme and Lisp share a common lineage, as Scheme is a dialect of Lisp.
  • Dynamic Typing: Both Scheme and Lisp use dynamic typing, as does Prolog.
  • Use of Lists: Lists are a central data structure in Scheme and Lisp, while Prolog relies heavily on lists for representing structured data.
  • Recursion: Recursion is a key programming tool in Scheme and Lisp, and Prolog uses recursion to define relationships.
  • Symbolic Computing: All three are well-suited for symbolic computation and problem-solving.
  • Immutability: Prolog and Scheme emphasize immutability, though Lisp supports mutable structures.
  • Interactive Development: All three languages provide REPLs (Read-Eval-Print Loops) for interactive programming.

4. Use Cases

  • Scheme: Academic settings, functional programming, and scripting.
  • Prolog: Artificial intelligence, knowledge representation, natural language processing, and theorem proving.
  • Lisp: AI research, symbolic computation, game development, and text editors (e.g., Emacs Lisp).


1. Scheme Function: member
Question:
Explain the purpose of the Scheme member function and provide an example of its usage.

Answer:
The member function checks whether an element exists in a list. If the element is found, it returns the sublist starting from that element; otherwise, it returns #f.

Example:

scheme
Copy code
(member 3 ‘(1 2 3 4)) ; Returns (3 4)
(member 5 ‘(1 2 3 4)) ; Returns #f
2. Scheme Function: equal?
Question:
What does the Scheme equal? function do? How is it different from eq? and eqv??

Answer:
The equal? function checks for structural equality, meaning it compares elements recursively for equality.

eq? checks object identity (memory location).
eqv? checks for value equivalence for primitive data types.
Example:

scheme
Copy code
(equal? ‘(1 2 3) ‘(1 2 3)) ; Returns #t
(eq? ‘(1 2 3) ‘(1 2 3))     ; Returns #f (different objects)
(eqv? 3 3)                  ; Returns #t
3. Scheme Function: composition
Question:
How do you compose two functions in Scheme? Write an example.

Answer:
Function composition in Scheme combines two functions so that the output of one becomes the input of the other.

Example:

scheme
Copy code
(define (square x) (* x x))
(define (add1 x) (+ x 1))
(define compose (lambda (f g) (lambda (x) (f (g x)))))
(define square-add1 (compose square add1))
(square-add1 3) ; Returns 16 (square(add1(3)))
4. Scheme Function: append
Question:
Describe the Scheme append function and provide an example.

Answer:
The append function concatenates two or more lists. It does not modify the original lists but creates a new one.

Example:

scheme
Copy code
(append ‘(1 2) ‘(3 4)) ; Returns (1 2 3 4)
(append ‘(a b) ‘())    ; Returns (a b)
5. Predicate Function: list?
Question:
What is the purpose of the list? predicate in Scheme? Provide an example.

Answer:
The list? function checks whether the given value is a proper list. It returns #t if it is a list and #f otherwise.

Example:

scheme
Copy code
(list? ‘(1 2 3)) ; Returns #t
(list? ‘())      ; Returns #t
(list? 42)       ; Returns #f
6. Predicate Function: null?
Question:
What does the null? predicate check in Scheme? Provide an example.

Answer:
The null? function checks whether a list is empty. It returns #t if the list is empty and #f otherwise.

Example:

scheme
Copy code
(null? ‘())      ; Returns #t
(null? ‘(1 2 3)) ; Returns #f
7. Functions: CAR, CDR, and CONS
Question:
Explain the functions CAR, CDR, and CONS in Scheme and provide examples.


Answer:

CAR: Returns the first element of a list.
CDR: Returns the rest of the list, excluding the first element.
CONS: Creates a new pair by prepending an element to a list.
Examples:

scheme
Copy code
(car ‘(1 2 3))   ; Returns 1
(cdr ‘(1 2 3))   ; Returns (2 3)
(cons 0 ‘(1 2 3)) ; Returns (0 1 2 3)
8. Special Features of Python
Question:
What are the special features of Python that make it popular among developers?

Answer: Readability: Python’s syntax is clean and emphasizes readability. Dynamic Typing: Variables do not require explicit type declarations. Rich Libraries: Extensive standard library for tasks like file handling, web scraping, and scientific computing.
Interpreted: Python code runs directly without compilation, allowing for rapid prototyping. Cross-Platform: Runs on various platforms like Windows, macOS, and Linux. Community Support: Active community with vast resources for learning and problem-solving.
9. Writing Python Code
Question:
Write Python code to demonstrate list operations, function definition, and class usage.

# List operations
numbers = [1, 2, 3, 4]
numbers.append(5)        # Add an element
print(numbers)           # Output: [1, 2, 3, 4, 5]
numbers.pop()            # Remove the last element
print(numbers)           # Output: [1, 2, 3, 4]

# Function definition
def square(x):
    return x * x

print(square(4))         # Output: 16

# Class usage
class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14159 * self.radius ** 2

circle = Circle(5)
print(circle.area())     # Output: 78.53975