Logic, Functional, and Object-Oriented Programming Concepts
Chapter 16: Logic Programming
What are the three primary uses of symbolic logic in formal logic?
Express propositions, express relationships, and infer conclusions.What are the two parts of a compound term?
Functor and arguments.What are the two modes in which a proposition can be stated?
Fact or rule.What is the general form of a proposition in clausal form?
Head :- Body.What are antecedents? Consequences?
Antecedents: Conditions (Body).
Consequences: Results (Head).Give general (not rigorous) definitions of resolution and unification.
Resolution: Infers new facts from existing ones.
Unification: Matches terms by finding a substitution.
What are the forms of Horn clauses?
Facts, rules, and queries.What is the basic concept of declarative semantics?
Logic specifies what to do, not how to do it.What does it mean for a language to be nonprocedural?
It specifies results without defining execution steps.What are the three forms of a Prolog term?
Constants, variables, and structures.What is an uninstantiated variable?
A variable without a value.What are the syntactic forms and usage of fact and rule statements in Prolog?
Fact: predicate(arguments).
Rule: head :- body.
What is a conjunction?
A sequence of goals joined by ,.Explain the two approaches to matching goals to facts in a database.
Unification and pattern matching.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.
Explain how backtracking works in Prolog.
When a goal fails, Prolog backtracks to try alternative solutions.Explain what is wrong with the Prolog statement K is K + 1.
Variables cannot be reassigned; K must already have a value.What are the two ways a Prolog programmer can control the order of pattern matching during resolution?
Ordering clauses and using the cut operator.Explain the generate-and-test programming strategy in Prolog.
Generate potential solutions and test their validity.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.Explain the negation problem with Prolog. Why is this a limitation?
Negation assumes closed-world assumption, leading to incorrect results with incomplete information.Explain the connection between automatic theorem proving and Prolog’s inferencing process.
Both rely on resolution and unification.Explain the difference between procedural and nonprocedural languages.
Procedural defines how tasks are performed; nonprocedural specifies what tasks are performed.Explain why Prolog systems must do backtracking.
To explore alternative solutions when goals fail.What is the relationship between resolution and unification in Prolog?
Resolution uses unification to infer new facts.
Chapter 15: Functional Programming
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.
What does a lambda expression specify?
An anonymous function.What data types were parts of the original Lisp?
Atoms and lists.In what common data structure are Lisp lists normally stored?
Linked lists.Explain why QUOTE is needed for a parameter that is a data list.
To prevent evaluation of the list as a function.What is a simple list?
A list containing only atomic elements.What does the abbreviation REPL stand for?
Read-Eval-Print Loop.What are the three parameters to IF?
Condition, true branch, false branch.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.
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.What are the two forms of DEFINE?
Define variables and define functions.Describe the syntax and semantics of COND.
A multi-way conditional in Scheme. Syntax: (COND (condition1 result1) … (else result)).Why are CAR and CDR so named?
From the IBM 704: “Contents of Address Register” and “Contents of Decrement Register.”If CONS is called with two atoms, say ‘A and ‘B, what is returned?
A pair: (A . B).Describe the syntax and semantics of LET in Scheme.
Binds variables to values in a local scope: (LET ((var1 val1) …) body).What are the differences between CONS, LIST, and APPEND?
CONS: Adds an element to a list.
LIST: Creates a new list.
APPEND: Combines lists.
Describe the syntax and semantics of mapcar in Scheme.
Applies a function to each element of a list: (MAPCAR function list).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.Why were imperative features added to most dialects of Lisp?
To increase flexibility and usability.In what ways are Common Lisp and Scheme opposites?
Common Lisp emphasizes features and libraries, while Scheme emphasizes simplicity.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.What happens during the reader phase of a Common Lisp language processor?
Translates code into internal data structures.
Chapter 15: continued
What are two ways that ML is fundamentally different from Scheme?
Stronger type system and pattern matching.What is stored in an ML evaluation environment?
Variable bindings and function definitions.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.What is type inferencing, as used in ML?
The compiler automatically deduces the types of expressions.What is the use of the fn reserved word in ML?
Introduces an anonymous function.Can ML functions that deal with scalar numerics be generic?
Yes, through parametric polymorphism.What is a curried function?
A function that takes multiple arguments one at a time.What does partial evaluation mean?
Evaluating a function with some arguments, creating a specialized function.Describe the actions of the ML filter function.
Returns a list containing only elements that satisfy a predicate.What operator does ML use for Scheme’s CAR?
hd.What operator does ML use for functional composition?
o.What is a strict programming language?
Evaluates function arguments before applying the function.What programming paradigms are supported by F#?
Functional, imperative, and object-oriented.With what other programming languages can F# interoperate?
.NET languages like C# and VB.NET.What does F#’s let do?
Defines variables or functions.How is the scope of a F# let construct terminated?
By indentation or the in keyword.What is the underlying difference between a sequence and a list in F#?
Sequences are lazy; lists are eager.What is the difference between the let of ML and that of F#, in terms of extent?
F#’s let can be recursive.What is the syntax of a lambda expression in F#?
(fun x -> expression).Does F# coerce numeric values in expressions? Argue in support of the design choice.
No, to maintain type safety.What support does Python provide for functional programming?
Functions like map, filter, and comprehensions.What function in Ruby is used to create a curried function?
Proc#curry.Is the use of functional programming expanding or shrinking?
Expanding, due to increased interest in parallelism and immutability.What is one characteristic of functional programming languages that makes their semantics simpler than that of imperative languages?
Referential transparency.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
Describe the three characteristic features of object-oriented languages.
Encapsulation, inheritance, and polymorphism.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.What is multiple inheritance?
A class inheriting from more than one parent class.What is a polymorphic variable?
A variable that can hold values of different types during execution.What is an overriding method?
A method in a subclass that redefines a method in its superclass.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.What is a virtual method?
A method defined to be dynamically bound.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.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.What is a nesting class?
A class defined within another class.What is the message protocol of an object?
The set of methods that can be called on the object.From where are Smalltalk objects allocated?
The heap.Explain how Smalltalk messages are bound to methods. When does this take place?
Dynamically at runtime.What type checking is done in Smalltalk? When does it take place?
None at compile-time; all type checking is done at runtime.What kind of inheritance, single or multiple, does Smalltalk support?
Single inheritance.What are the two most important effects that Smalltalk has had on computing?
Popularized object-oriented programming and graphical user interfaces.In essence, all Smalltalk variables are of a single type. What is that type?
Object.From where can C++ objects be allocated?
Stack, heap, or static memory.How are C++ heap-allocated objects deallocated?
Using the delete operator.Are all C++ subclasses subtypes? If so, explain. If not, why not?
No, only if they satisfy the Liskov Substitution Principle.Under what circumstances is a C++ method call statically bound to a method?
When the method is not declared as virtual.What drawback is there to allowing designers to specify which methods can be statically bound?
Potential for runtime errors when dynamic behavior is needed.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.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.
- Chapter 12 continued
How are parameters sent to a superclass’s constructor in C++?
Using an initializer list in the subclass constructor.What is the single most important practical difference between Smalltalk and C++?
Smalltalk is fully dynamic; C++ is statically typed.How is the type system of Java different from that of C++?
Java uses runtime type checking; C++ has static type checking.From where can Java objects be allocated?
The heap.What is boxing?
Converting a primitive type to its corresponding object wrapper.How are Java objects deallocated?
By the garbage collector.Are all Java subclasses subtypes?
Yes, because Java enforces the Liskov Substitution Principle.How are superclass constructors called in Java?
Using super.Under what circumstances is a Java method call statically bound to a method?
When the method is declared as final or static.In what way do overriding methods in C# syntactically differ from their counterparts in C++?
C# uses the override keyword explicitly.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().How does Ruby implement primitive types, such as those for integer and floating-point data?
As objects.How are getter methods defined in a Ruby class?
Using attr_reader.What access controls does Ruby support for instance variables?
Private access by default.What access controls does Ruby support for methods?
Public, private, and protected.Are all Ruby subclasses subtypes?
No, Ruby does not enforce the Liskov Substitution Principle.Does Ruby support multiple inheritance?
No, but it supports mixins using modules.What does reflection allow a program to do?
Inspect or modify its structure and behavior at runtime.In the context of reflection, what is metadata?
Information about the program’s structure, such as class and method definitions.What is introspection?
The ability of a program to examine its structure at runtime.What is intercession?
The ability of a program to modify its structure at runtime.What class in Java stores information about classes in a program?
Class.For what is the Java name extension .class used?
For storing compiled bytecode.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
What are the two kinds of abstractions in programming languages?
Process abstraction and data abstraction.Define abstract data type.
A data type defined by its behavior (operations) rather than its implementation.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).What are the language design requirements for a language that supports abstract data types?
Syntax for defining ADTs, access control, and encapsulation mechanisms.What are the language design issues for abstract data types?
Access control, type-checking mechanisms, and parameterized types.From where are C++ objects allocated?
Stack, heap, or static memory.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.What is the purpose of a C++ constructor?
To initialize an object’s data members.What are the legal return types of a constructor?
Constructors do not have a return type.Where are all Java methods defined?
Inside a class.How are C++ class instances created?
On the stack (automatic) or the heap (dynamic).From where are Java class instances allocated?
The heap.Why does Java not have destructors?
Java uses garbage collection to manage memory.Where are all Java methods defined?
Inside classes.Where are Java classes allocated?
In the heap.Why are destructors not as frequently needed in Java as they are in C++?
Automatic garbage collection.What is a friend function? What is a friend class?
A function or class with special access to private/protected members of another class.What is one reason Java does not have friend functions or friend classes?
To enforce stricter encapsulation and avoid access abuse.Describe the fundamental differences between C# structs and its classes.
Structs are value types, while classes are reference types.How is a struct object in C# created?
On the stack, unless explicitly boxed.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.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.What is the name of all Ruby constructors?
initialize.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.How are instances of C++ template classes created?
By specifying a type during instantiation.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.What problems can occur using C to define abstract data types?
Lack of access control and encapsulation.What is a C++ namespace, and what is its purpose?
A container for identifiers to prevent naming conflicts.What is a Java package, and what is its purpose?
A grouping mechanism for related classes to provide modularity and avoid naming conflicts.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
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.What does it mean for a subprogram to be active?
A subprogram is active when its execution has begun but not yet completed.What is given in the header of a subprogram?
Its name, parameters, and possibly the return type.What characteristic of Python subprograms sets them apart from those of other languages?
They can have default parameter values and support keyword arguments.What languages allow a variable number of parameters?
C, C++, Python, Ruby, and JavaScript.What is a Ruby array formal parameter?
A parameter that captures a variable number of arguments into an array.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.What are formal parameters? What are actual parameters?
Formal parameters: Defined in the subprogram.
Actual parameters: Passed by the caller during invocation.What are the advantages and disadvantages of keyword parameters?
Advantages: Improved readability and flexibility.
Disadvantages: Increased verbosity and potential for errors if mismatched.What are the differences between a function and a procedure?
Functions return a value; procedures do not.What are the design issues for subprograms?
Parameter passing, local variables, recursion, and nesting.What are the advantages and disadvantages of dynamic local variables?
Advantages: Flexibility and memory efficiency.
Disadvantages: Overhead in allocation/deallocation and potential side effects.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.What languages allow subprogram definitions to be nested?
Ada, Python, and JavaScript.What are the three semantics models of parameter passing?
Pass-by-value, pass-by-result, and pass-by-reference.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.
Describe the ways that aliases can occur with pass-by-reference parameters.
Aliases can occur when multiple parameters reference the same memory location.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.What are two fundamental design considerations for parameter-passing methods?
Efficiency and safety.Describe the problem of passing multidimensioned arrays as parameters.
Dimensions must be explicitly declared or passed, complicating syntax and implementation.What is the name of the parameter-passing method used in Ruby?
Pass-by-reference-value.What are the two issues that arise when subprogram names are parameters?
Binding the subprogram name and its referencing environment.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:
What is an overloaded subprogram?
A subprogram with the same name but different parameter profiles.What is parametric polymorphism?
The ability to write subprograms that can operate on any data type.What causes a C++ template function to be instantiated?
Calling the function with a specific data type.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.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.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.What are the design issues for functions?
Return types, recursion, and parameter handling.Name two languages that allow multiple values to be returned from a function.
Python and Ruby.What exactly is a delegate?
A reference to a method, commonly used in C# for callbacks.What is the main drawback of generic functions in F#?
Lack of runtime type information.What is a closure?
A function with an associated referencing environment.What are the language characteristics that make closures useful?
First-class functions and lexical scoping.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
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).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.What does the range function in Python do?
Generates a sequence of numbers within a specified range.What contemporary languages do not include a goto?
Python, Java, and modern functional languages.What are the design issues for logically controlled loop statements?
Syntax, condition evaluation, and exit mechanisms.What is the main reason user-located loop control statements were invented?
To provide greater control over loop termination or continuation.What are the design issues for user-located loop control mechanisms?
Readability, flexibility, and effect on nested loops.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.What are the differences between the break statement of C++ and that of Java?
Java allows labeled breaks; C++ does not.What is a user-defined iteration control?
Using constructs like iterators or higher-order functions to define iteration behavior.What Scheme function implements a multiple selection statement?
COND.How does a functional language implement repetition?
Through recursion.How are iterators implemented in Ruby?
With blocks and methods like each.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
What is the definition of control structure?
A mechanism that controls the flow of execution in a program (e.g., sequence, selection, iteration).What did Böhm and Jacopini prove about flowcharts?
All algorithms can be implemented using only three control structures: sequence, selection, and iteration.What is the definition of block?
A sequence of statements treated as a single unit of execution.What is/are the design issue(s) for all selection and iteration control statements?
Number of branches, syntax, type checking, and nesting rules.What are the design issues for selection structures?
Form of expression, multiple branches, and rules for nesting.What is unusual about Python’s design of compound statements?
Python uses indentation instead of braces or delimiters to define compound statements.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.What are the common solutions to the nesting problem for two-way selectors?
Using keywords like endif or restructuring code with explicit blocks.What are the design issues for multiple-selection statements?
Evaluation method for conditions, execution of multiple segments, and readability.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.What is unusual about C’s multiple-selection statement?
The switch statement allows fall-through between cases unless explicitly prevented with a break.On what previous language was C’s switch statement based?
ALGOL W.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.What are the design issues for all iterative control statements?
Type of iteration (pretest, posttest, or midtest) and control mechanisms.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
Aspect | Scheme | Prolog | Lisp |
---|---|---|---|
Paradigm | Functional programming | Logic programming | Functional programming |
Execution Model | Expression evaluation, recursion-centric | Resolution and unification for goal satisfaction | Expression evaluation, recursion-centric |
Syntax | Minimalistic and clean ((operator operand operand) ) | Rule-based with facts, rules, and queries | Parentheses-heavy ((operator operand operand) ) |
Typing | Dynamically typed | Dynamically typed | Dynamically typed |
Use of Variables | Lexically scoped and immutable | Logical variables; single-assignment | Lexically scoped and mutable |
Primary Data Types | Lists, symbols, numbers | Facts, rules, queries | Lists, symbols, numbers |
Evaluation Order | Eager evaluation | Backtracking with depth-first search | Eager evaluation |
Primary Use Case | Functional programming and teaching | Knowledge representation and AI | General-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