LMU ☀️ CMSI 585
PROGRAMMING LANGUAGE FOUNDATIONS
Practice Problems

Here are some long-form exercises for you to work on to improve understanding and retention of course content. Short-form recall questions, designed to be part of your spaced-repetition learning regimen, can be found at the bottom of each page of course notes.

Logic

  1. Define deduction, induction, and abduction in your own words.
  2. Translate the following sentences into logical notation.
    1. If you don't leave now, you will not win the prize.
    2. Ani or her sisters might have been late.
    3. Some dogs like cats who live in the capital of Turkey.
    4. The person who won the race prefers orange juice to tea.
    5. $3$ will never be greater than $7$.
    6. Not every odd number is greater than its own square.
    7. Something evil caused all evil things except itself.
    8. Some day, it will be possible that all players will have the same score.
    9. War is peace, freedom is slavery, and ignorance is strength.
    10. All that was once true will someday necessarily be forever false.
    11. 75% of Creation Museum attendees believe Jesus rode dinosaurs to church.
    12. Your best friend must help you out of every jam.
    13. It is not okay to lie.
    14. You are allowed to not believe that everyone is telling the truth.
    15. If you know what is on the test, you will probably get a good score.
    16. Juliet once believed that Socrates was real, but no longer does.
    17. Everyone who attended Lollapalooza in 2025 was more likely to have a good time if they took public transportation or carpooled.
    18. No one knows if Goldbach’s Conjecture is true.
    19. Tanya wrote her book about logic swiftly and eloquently.
    20. The set of all rational numbers less than $\sqrt{2}$ has no greatest element.
    21. Romeo doesn’t know that he is doomed.
  3. Give three ambiguous English sentences that could be interpreted as either $A \supset \Box B$ or $\Box (A \supset B)$, such that one of the formulae is false in our world and the other true. Then give renderings of each formula in English that would not be ambiguous.
  4. For each of the following, identify whether these longhand (non-single-letter) parts of formulas are (1) most likely a function, (2) most likely a predicate, or (3) pretty much 50-50 ambiguous.
    1. $\mathit{even}$
    2. $\mathit{oldestSister}$
    3. $\mathit{isSisterOf}$
    4. $\mathit{plus}$
    5. $\mathit{lessThan}$
    6. $\mathit{hasSiblings}$
    7. $\mathit{square}$
    8. $\mathit{french}$
  5. For each of the following, identify whether it is a term or a formula or neither.
    1. $\mathit{Romeo}$
    2. $\mathit{Likes}$
    3. $\mathit{Likes}\,(\mathit{Romeo}, \mathit{Juliet})$
    4. $\mathit{WeddingOfficiator}\,(\mathit{Romeo}, \mathit{Juliet})$
    5. $\exists c. \Box \textbf{G} (Ac)$
    6. $\iota c. \Box \textbf{G} (Ac)$
  6. A ________________ can be thought of as a predicate with no arguments.
  7. A ________________ can be thought of as a function with no arguments.
  8. Why is it that in predicate logic, you actually do not need functions?
  9. For each of the following, rewrite in its fully parenthesized form. Do not let the spacing fool you. Stick to the precedence and associativity rules.
    1. $\neg A \lor B \supset C \land D \equiv E \land \neg F$
    2. $A \lor B \lor B \lor \forall x. \exists y. A\,x \lor B$
    3. $A \supset B \supset (\exists x. \Box \lozenge C(f\;g\;x)) \lor \forall y. \neg D\,y$
    4. $\exists x. P x \;\land\; \exists y. Q y$
  10. For each of the following, circle the free occurrences of variables. Do not let the spacing fool you. Stick to the precedence and associativity rules.
    1. $\forall x. P\,x \lor Q\,y \;\supset\; \exists y. P\,y \land Q\,x$
    2. $\forall x. \exists y. P\,x\,y \lor Q\,y$
    3. $\neg \forall x. P\,x \;\land Q\,x$
    4. $Q\,R\,t \supset (\iota t. P\,t) \gt t$
    5. $\mathscr{K}_xHx \lor x = t$
  11. Evaluate each of the following. As always, be careful about parentheses and variable renaming:
    1. $(P\,x)[x \mapsto y]$
    2. $(P\,x)[x \mapsto f\,x]$
    3. $(\forall x. P\,x\,y)[x \mapsto y]$
    4. $(\forall y. P\,x\,y)[x \mapsto y]$
    5. $(x \land \exists x. P\,x)[x \mapsto y]$
    6. $(\forall x. \exists y. P\,x\,y)[x \mapsto y]$
    7. $(\forall x. \exists y. P\,(f\,x\,y))[x \mapsto f\,y]$
    8. $(\forall f. \exists y. P\,(f\,x\,y))[x \mapsto f\,y]$
  12. Is it the case that, when substituting $t$ for $x$ in $A$, then variable renaming is necessary if and only if $t$ is not free for $x$ in $A$? Why or why not?
  13. Write judgments for the following:
    1. Truth is necessarily true.
    2. Assuming that Mercury is in retrograde, it is possible that you will have a bad day.
    3. Something is good assuming not everything is bad.
    4. Assuming $x$ has type integer and $y$ has type natural, then $\frac{x}{y+1}$ has type rational.
  14. What is this logical argument stating, in plain English? $$ \frac{\forall P.\,P \supset \lozenge \mathscr{K}P}{\Box \mathscr{K}P} $$
  15. Is the Catuṣkoṭi bivalent? Why or why not?
  16. How does a classical logic handle, or not handle, the case of a wish grantee saying to a Genie “I wish this wish not be granted“? How is it handled in a multi-valued logic?
  17. What operators appear in predicate logic but not propositional logic?
  18. Translate each of the eight syllogistic forms into predicate logic.
  19. Why might the commutativity of conjunction, a pillar of classical logic, be controversial in non-classical contexts?
  20. What are the three main things you cannot do in intuitionistic logic that you can do in classical logic?
  21. Argue why $\mathscr{O}$ and $\mathscr{P}$ are duals in (classical) deontic logic.
  22. What is the difference between epistemic and doxastic logic?
  23. Are the (classical) temporal operators $\textbf{F}$ and $\textbf{G}$ duals of each other? Why or why not?
  24. In what sense is a formal system just a part of a logical system? What is it missing that a logical system provides?
  25. Given the interpretation ${p: \textrm{false}, q: \textrm{true}, r: \textrm{false}}$, compute the truth value of the following formulas:
    1. $p \lor q$
    2. $p \land q$
    3. $p \supset q$
    4. $\neg p$
    5. $\neg \neg \neg \neg r$
    6. $(p \lor q) \land r \equiv (\neg p \land q) \land \neg r$
    7. $\neg p \lor q \equiv \neg q \supset \neg p$
    8. $r \lor p \equiv p \supset r \land \neg r \lor T \land (r \equiv p)$
  26. Complete the following truth table for propositional logic.
    $A$$B$$\;\;\neg A\;\;$$\;\;\neg B\;\;$$A \land B$$A \lor B$$A \supset B$$A \equiv B$
    truetrue      
    truefalse      
    falsetrue      
    falsefalse      
  27. Complete the following truth table for propositional logic, where $A \uparrow B$ means $A$ NAND $B$, $A \downarrow B$ means $A$ NOR $B$, and $A \oplus B$ means $A$ XOR $B$, and $A \subset B$ means $B$ materially implies $A$.
    $A$$B$$A \uparrow B$$A \downarrow B$$A \oplus B$$A \subset B$
    truetrue    
    truefalse    
    falsetrue    
    falsefalse    
  28. Complete the following truth table for a three-valued logic, assuming your goal is truth-preservation.
    $A$$B$$\;\;\neg A\;\;$$\;\;\neg B\;\;$$A \land B$$A \lor B$$A \supset B$$A \equiv B$
    truetrue      
    truefalse      
    trueother      
    falsetrue      
    falsefalse      
    falseother      
    othertrue      
    otherfalse      
    otherother      
  29. Complete the following truth table for a three-valued logic, assuming your goal is falsity-avoidance.
    $A$$B$$\;\;\neg A\;\;$$\;\;\neg B\;\;$$A \land B$$A \lor B$$A \supset B$$A \equiv B$
    truetrue      
    truefalse      
    trueother      
    falsetrue      
    falsefalse      
    falseother      
    othertrue      
    otherfalse      
    otherother      
  30. For each of propositional logic, first order predicate logic, and higher order logic, give three formulae: one that is valid (a tautology), one that is satisfiable but not valid (a contingency), and one that is unsatisfiable (a contradiction).
  31. Suppose that you had a classical, bivalent logistic system powerful enough to express statements about the provability of its own formulas, for example, “This formula is not provable” or equivalently “I am not provable.” Show that such a system, if consistent, must be incomplete, and if complete, must be inconsistent.

Foundations of Mathematics

  1. What is the reason for the restriction to pairwise disjoint sets in Zermelo’s original formulation of the Axiom of Choice?
    Without the restriction, $C$ could accidentally hit two elements of some $A$ that it shares with a different member of $\mathfrak{A}$, and the exactly one guarantee can fail outright. To see this, note that no such $C$ exists for $\{\{1,2\},\{2,3\},\{1,3\}\}$.
  2. Simplify each of the following as much as possible without introducing any roundoff errors. Your simplified expressions must still be exact:
    1. $3 \uparrow \uparrow 2$
    2. $2 \uparrow \uparrow \uparrow 3$
    3. $790912853^{3892359} \;\mathtt{mod}\; 90277$
    4. $(3 + 2i - 8k) \times (8i + 2j -k)$       (quaternion multiplication)
    5. $\log_8{2^{333333333}}$

Set Theory

  1. Mark each of the following as true or false:
    1. $\varnothing \in \varnothing$
    2. $\varnothing \in \{ \varnothing \}$
    3. $\varnothing \subseteq \varnothing$
    4. $\varnothing \subseteq \{ \varnothing \}$
    5. $\{ x, y \} \subseteq \mathcal{P}(\{ x, y, \{x,y\} \})$
    6. $\mathcal{P}(\varnothing) = \{ \varnothing \}$
    7. $\{ x, y, z\}^3 - \{ s \;\mid\; |s| \leq 3 \} \neq \varnothing$
    8. $\bigcup \{ \mathbb{N}, \mathbb{B}, \mathbb{Q} \} - \mathbb{B} = \mathbb{Q}$
    9. $(9, 3, F) \in \mathbb{Z} \times \mathbb{B} \times \mathbb{R} \wedge (1,2)\!\downarrow\!1 = 2$
    10. $|\mathcal{P}(\{a,b,c\}) - \mathcal{P}(\{a,b\})| = 5$
  2. Show that the modern phrasing of the Axiom of Choice, which states the existence of a choice function that selects one element from each set does not require pairwise disjoint sets.
  3. Is the intersection of two partial orders a partial order? If so, prove it. If not, give a counterexample.

Type Theory

Lambda Calculus

  1. Let $f = \lambda x. 2x + 1$ and $g = \lambda x. \lambda y. 3xy$. Reduce each of the following expressions (or if they cannot be reduced, say why):
    1. $f^5(20)$
    2. $f \circ f$
    3. $g(f[5/3](3) - f[5/3](2))$
    4. $(\lambda w. (f^{-1}(71), w(5), w(1)))(f \circ (g\:1)) $
    5. $(\lambda x. (x\:x))(\lambda x. (x\:x))$

Language Theory

  1. Give generative grammars for the following mini-languages:
    1. Odd-length Palindromes of strings made from Unicode letters only
    2. All strings over the alphabet ${a, b, c, d, e}$ where the symbols are in decreasing alphabetic order
    3. $\{ 0^i1^j2^k \mid i=j \vee j=k \}$
    4. $\{ w \in \{0,1\}^* \mid w \textrm{ does not contain the substring 000} \}$
    5. $\{ w \in \{a,b\}^* \mid w \textrm{ has twice as many $a$'s as $b$'s} \}$
    6. (EXTRA CREDIT) $\{ a^nb^na^nb^n \mid n \geq 0 \}$
  2. Give an analytic grammar, using the notation from class, for the programming language described as follows. Programs are made up of a possibly empty sequence of function declarations, followed by a single expression. Each function declaration is of the form $f = (p_1, \ldots, p_m) \Rightarrow e$ where $f$ is the function name (an identifier), each $p_i$ is a parameter (also identifiers) and the result (the “body”) is an expression. Expressions can be numeric literals, string literals, identifiers, function calls, or can be made up of other expressions with the usual binary arithmetic operators (plus, minus, times, divide, remainder) and a unary prefix negation and a unary postfix factorial (!). There’s a conditional expression with the syntax x ? y : z. Parentheses are used, as in most other languages, to group subexpressions. Numeric literals are non-empty sequences of decimal digits with an optional fractional part and an optional exponent part. String literals delimited with double quotes with the escape sequences \', \", \n, \\, and \u{$hhhhhh$} where $hhhhhh$ is a sequence of one-to-six hexadecimal digits. Identifiers are non-empty sequences of letters, decimal digits, underscores, and dollar signs, beginning with a letter or dollar sign. Function calls are formed with an identifier followed by a parenthesized, comma-separated list of expressions.

Syntax

  1. Draw the concrete syntax tree for the expression 8 * (13 + 5), assuming a grammar with variables named Expression, Term, Factor, Primary, and intlit.
          Expression
              |
            Term
          /   |   \
      Term    *    Factor
        |       /    |     \
     Factor   (  Expression  )
        |         /    |  \
    Primary Expression +  Term
        |         |         |
     intlit     Term      Factor
                  |         |
               Factor    Primary
                  |         |
               Primary    intlit
                  |
               intlit
    
  2. Draw the abstract syntax tree for the expression 8 * (13 + 5).
        *
      /   \
    8      +
          /  \
        13    5
    
  3. Give an Ohm grammar for expressions in a language in which:
    • The lowest precedence operators are the binary unless, if, while, and until operators, which are non-associative.
    • The next lowest precedence operators are the logical binary operators, which are left associative amongst themselves, but do not associate with each other, meaning that one while can write A and B and C, one may not write A and B or C.
    • The next lowest precedence operators are the relational operators (<, <=, ==, !=, >=, and >), which are non-associative.
    • Next in precedence come the left associative shift operators (<< and >>)
    • Next come the left multiplicative operators (*, /, and %)
    • Next come the left associative additive operators (+ and -)
    • Next come the right associative exponentiation operator (**)
    • Next come non-associative unary operators. The unary operators - and not are prefix, while ! (for factorial) is postfix. Because these are non-associative, one cannot write - - 2 or -5! or 3!!!.
    • The most primitive expressions are identifiers, numeric literals, string literals, ranges (of the form [e1 .. e2] for expressions e1 and e2), function calls, and of course, parenthesized expressions.

    Assume the existence of variables id, numlit, stringlit, and Call.

  4. Give the phrase syntax of a little language with integer-valued variables, assignment statements, while statements, read and write statements, and the usual arithmetic, relational operators, such that type checking between integers and booleans is done in the syntax. Hint: you will need separate sets of variables for arithmetic and logical expressions.
    Program   =  Block
    Block     =  (Stmt ";")+
    Stmt      =  Id "=" Exp
              | read Id ("," Id)*
              | write Exp ("," Exp)*
              | while BoolExp loop Block end
    Exp       =  Exp1 (("+" | "-") Exp1)*
    Exp1      =  Exp2 (("*" | "/") Exp2)*
    Exp2      =  "-"? Exp3
    Exp3      =  intlit | id | "(" Exp ")"
    BoolExp   =  BoolExp1 (or BoolExp1)*
    BoolExp1  =  BoolExp2 (and BoolExp2)*
    BoolExp2  =  Exp (("<" | "<=" | "==" | "!=" | ">=" | ">") Exp)?
              | BoolExp3
    BoolExp3  =  not? BoolExp4
    BoolExp4  =  true | false | "(" BoolExp ")"
    
  5. Give the abstract syntax tree for the following C++ expression
    (a = 3) >= m >= ! & 4 * ~ 6 || y %= 7 ^ 6 & p
    
  6. Give the abstract syntax for the following C fragment:
    int f(int x, int y) {
       return y,x?a.p[5]+=7&!y<x<y+++x||+x|*&y-~--y*x^y:0;
    }
    
  7. Give the abstract syntax for the following C fragment:
    printf("%08X %#16.7e\n",x---a.p[9]^x|*&p&1,*((float*)&x));
    
  8. Give the abstract syntax tree for the following Perl fragment (die and split are both list operators):
    die "\n">>1,~\$$x^split @a,3|x**$;=>%p&&&p;
    
  9. Here is the description of a language. Programs are made up of a non-empty sequence of function declarations, terminated by semicolons, followed by a single expression. Each function declaration starts with the keyword fun followed by the function's name (an identifier), then a parenthesized list of zero or more parameters (also identifiers) separated by commas, then an equals sign, then the body which is a single expression. Expressions can be numeric literals, string literals, identifiers, function calls, or can be made up of other expressions with the usual binary arithmetic operators (plus, minus, times, divide) and a unary prefix negation and a unary postfix factorial ("!"). There is also an infix binary operator called then which indicates that both of its expressions be evaluated in order from left to right, with the value of the right expression being the value of the entire then-expression. There's a conditional expression that looks just like the one in Java, C, and Perl (with the question mark and colon). Factorial has the highest precedence, followed by negation, the multiplicative operators, the additive operators, conditional and finally the then operator. Parentheses are used, as in most other languages, to group subexpressions. Numeric literals are non-empty sequences of decimal digits with an optional fractional part and an optional exponent part. String literals are as in C. Identifiers are those non-empty sequences of letters, decimal digits, underscores, at-signs, and dollar signs, beginning with a letter or dollar sign, that are not also reserved words. Function calls are as in C, with the arguments in a comma-separated list of expressions bracketed by parentheses. There are no comments in this language, and whitespace can be used liberally between tokens.
    1. Write an example program in this language that shows off everything described above.
    2. Give a syntax for this language.
    3. Write a program in this language that consists of the declaration of the GCD function followed by a call to this function with the arguments 99 and 66.
    4. Show the abstract syntax tree for your GCD program.
  10. In Lisp and its dialects, most of the arithmetic operators are defined to take two or more arguments, rather than strictly two. Thus (* 2 3 4 5) evaluates to 120, and (– 16 9 4) evaluates to 3. Show that parentheses are necessary to disambiguate arithmetic expressions in Lisp (in other words, give an example of an expression whose meaning is unclear when parentheses are removed). Why then, does the author Michael L. Scott say in his book that “Issues of precedence and associativity do not arise with prefix or postfix notation?” Reword this claim to make explicit the hidden assumption.
    Scott is assuming all operators have a fixed arity. What he meant to say was: “Issues of precedence and associativity do not arise with prefix or postfix notation assuming all operators have fixed arity.”
  11. For the language in the previous problem, write an abstract syntax specification. Use only the first of the two notations for tree grammars presented in the course notes on syntax.
  12. For the language in the previous problem, give an abstract syntax tree for the program:

    gcd = (x, y) => y ? gcd(y, x % y) : x
    cube = (x) => x * x * x
    "The answer is" + cube(gcd(30, 4!)) + "😦😦"
    
  13. For the following complete JavaScript program, draw the AST, using the level of detail we used during class. You can use my JavaScript AST explorer to guide you and check your work, but remember, the drawing you need to produce for full credit will be far less verbose than the explorer’s output (which is based on a third-party parser).

    import x from "x"
    console.log(93.8 * {x} << x.r[z])
    

Semantics

  1. TODO: Write a denotational semantics for...
  2. TODO: Write an operational semantics for...

Names, Scopes, and Bindings

  1. Give three examples from C which a variable is live but not in scope. Make sure each example is of a different quality than the others; for example, don't just hide three global variables in a single function and claim you have three examples.
  2. This fragment of Java code illustrates something about scope. Or does it? Relate it to other similar problems we've seen regarding scope. (Don't forget to come across as being articulate and intelligent in your discussion.)
    public void fail() {
        class Failure extends RuntimeException {}
        throw new Failure();
    }
    
  3. Show the output of the following, assuming dynamic scope and (a) deep binding, and (b) shallow binding.
    function g(h) {
      var x = 2;
      h()
    }
    
    function main() {
      var x = 5
      function f() {
        print x + 3
      }
      g(f)
    }
    
    main()
    
    (a) 8, (b) 5
  4. Show the output of the following, assuming dynamic scope and (a) deep binding, and (b) shallow binding.
    function f(a) {
      let x = a - 1
      function g() {
        print x - 17
      }
      h(g)
    }
    function h(p) {
      let x = 13
      p()
    }
    f(18)
    
  5. Explain what would need to be done to make deep binding work with dynamic scoping, assuming that association lists were used to implement the scope rules. (Hint: think of turning the association lists into "A-trees".)
    When you call the passed function, save the existing pointer to the top of the association list and replace it with a pointer to just before the point that the function was defined. Then enter the bindings for the new function as a "branch" in the association list (which is now a tree). When the function finally returns, chop off that branch and restore the pointer.

Types

  1. Is JavaScript 100% weakly typed? About what percentage is it? Why, exactly, is it not?
    No, JavaScript is not 100% weakly typed; The values null and undefined do not get coerced to objects, and non-functions do not get coerced to functions. I would say it's roughly 90% weakly typed. It’s not 100% weakly typed because its designer thought that coercing things to functions and even objects would be going too far, since there is no consensus on the obvious coercion to make.
  2. In the Java programming language, if the class Dog were a subclass of class Animal, then objects of class Dog[] would be compatible with the type Animal[]. Write a fragment of Java code that shows that this means that Java is not completely statically typed. Include in your answer a well-written explanation that shows you truly understand the difference between static and dynamic typing.
    If both Dog and Rat are subclasses of Animal, this code
      Animal[] pets = new Dog[4];
      pets[0] = new Rat();
    
    compiles fine but when executed throws an ArrayStoreException, that's right, a run-time typecheck error. This means Java is NOT 100% statically typed because this typecheck occurs at run time. A language can only be called 100% statically typed if all type conflicts are detected at compile time.
  3. Here's a variation of M-J. Dominus' Spectacular Example.
    local
        fun split [] = ([],[])
          | split [h] = ([h], [])
          | split (x::y::t) = let val (s1,s2) = split t in (x::s1,y::s2) end
        fun merge c ([], x) = x
          | merge c (x, []) = x
          | merge c (h1::t1, h2::t2) =
              if c(h1,h2)<0 then h1::merge c(t1,h2::t2) else h2::merge c(h1::t1,t2);
    in
        fun sort c [] = []
          | sort c x = let val (p, q) = split x
                         in merge c(sort c p, sort c q)
                       end;
       end;
    
    1. During type inference, give the types assigned to
      • the parameter c within sort
      • the function split
      • the function merge
      • the y in the third clause of split?
    2. Give the type of sort and explain why it is not what you would expect.
    3. How do you rewrite the function to make it actually do a mergesort?
  4. Here's some code in some language that looks exactly like C++. It is defining two mutually recursive types, A and B.
    struct A {B* x; int y;};
    struct B {A* x; int y;};
    
    Suppose the rules for this language stated that this language used structural equivalence for types. How would you feel if you were a compiler and had to typecheck an expression in which an A was used as a B? What problem might you run into?
  5. Consider the following C declaration, compiled on a 32-bit little endian machine:
    struct {
        int n;
        char c;
    } A[10][10];
    
    If the address of A[0][0] is 1000 (decimal), what is the address of A[3][7]?
  6. Explain the meaning of the following C declarations:
    double *a[n];
    double (*b)[n];
    double (*c[n])();
    double (*d())[n];
    
  7. Consider the following declaration in C:
    double (*f(double (*)(double, double[]), double)) (double, ...);
    
    Describe rigorously, in English, the type of $f$.

Pointers and References

  1. If possible, write a program in Go that makes a variable point to itself. That is, for some variable x, make it so that *x == x. If this is not possible, state why it is not possible.
  2. If possible, write a program in Rust that makes a variable point to itself. That is, for some variable x, make it so that *x == x. If this is not possible, state why it is not possible.
  3. If possible, give C++ type and object declarations to make a variable point to itself, that is, make it so that p == *p. If it is not possible to do so, state why no such variable can be defined.
  4. In C++ you can say (x += 7) *= z but you can't say this in C. Explain the reason why, using precise, technical terminology. See if this same phenomenon holds for conditional expressions, too. What other languages behave like C++ in this respect?

Control Flow

  1. The following pseudocode shows a midtest loop exit:
    while (true)
        line := readLine();
        if isAllBlanks(line) then exit end;
        consumeLine(line);
    end;
    
    Show how you might accomplish the same task using a while or repeat loop, if midtest loops were not available. (Hint: one alternative duplicates part of the code; another introduces a Boolean flag variable.) How do these alternatives compare to the midtest version?
  2. Assume we wanted to write a function called If in Java or C or JavaScript, such that the call If(c, e1, e2) would return e1 if c evaluated to true, and e2 if it evaluated to false. Show why, in these languages, such a function is absolutely not the same as the conditional expression c?e1:e2. You can show a code fragment that would return different results based on whether the function were called versus the conditional expression were evaluated.
    In Java, C, and JavaScript, all function arguments are evaluated before they are called. The evaluation of (p==null ? null : p.value) is null-safe, whereas the call If(p==null, null, p.value) is not: it throws a NullPointerException if p is null. A more blatant example can be seen in the difference between (true ? 1 : formatMyHardDrive()) and If(true, 1, formatMyHardDrive()).

Functions

  1. Some languages do not require the parameters to a subroutine call to be evaluated in any particular order. Is it possible that different evaluation orders can lead to different arguments being passed? If so, give an example to illustrate this point, and if not, prove that no such event could occur.
  2. In C++ it is not permitted to have two functions that differ only in return type overload each other. In Ada it is allowed. What is the reason for this situation? Even though other languages do allow this flexibility in overloading, the compiler needs some sophistication. What exactly is involved? Be very precise in your explanation and illustrate it with code fragments.
  3. Write a function that takes in a function f and a list [a0, a1, ..., an-1] and returns the list [a0, f(a1), f(f(a2)), f(f(f(a3))), ...].

    For example, if you pass as arguments the function that doubles its inputs, and the list [4, 3, 1, 2, 2], then the return value would be [4, 6, 4, 16, 32].

    Hint: Do the f(f(f...)) as a separate function. Also you do not have to make your function tail recursive.

  4. Write a tail-recursive JavaScript function that produces the sum of squares in an array. This is just to give you practice with tail-recursion; I know there are better ways to compute the sum-of-squares.
    function ss(a) {
      function s(i, acc) {
        return i == a.length ? acc : s(i+1, a[i]*a[i]+acc)
      }
      return s(0, 0);
    }
    
  5. Write a tail-recursive Ruby method that produces the sum of squares in an array. This is just to give you practice with tail-recursion; I know there are better ways to compute the sum-of-squares.
    def ss(a)
      s = Proc.new{|i,acc| i==a.length ? acc : s[i+1, a[i]*a[i]+acc]}
      s[0, 0]
    end
    
  6. In as many languages as you can (but include C, Java, JavaScript, and Python for sure), write a pair of functions, f and g, such that every time you call f, you get back 5 less than the result of the previous call to f or g, and every time you call g, you get back double the absolute value of the result of the last call to f or g. The initial value is 0. It is possible to do this in one line of Perl.
  7. Write the following function in Standard ML, where your implementation must be tail recursive.

    Given: a list [a0, a1, ..., an-1],
    Return: a0*a1 + a2*a3 + a4*a5 + ....

    For example, if given [3, 5, 0, 28, 4, 7] we return 15 + 0 + 28 = 43. If there are an odd number of elements in the list, assume there is an extra 1 for padding.

    Here is, by the way, a non-tail-recursive formulation:

    fun sum_of_prods [] = 0
      | sum_of_prods (x::nil) = x
      | sum_of_prods (x::y::t) = x * y + sum_of_prods t;
    
  8. Write a JavaScript function, without using eval, that accepts an array of integers a, and a function f, and returns an array of functions, each of which, when called, invokes f on the corresponding element of a.

    For example, if your function was called g, then calling g([6,3,1,8,7,9], dog) would return an array of functions p such that, for example, calling p[3]() would invoke dog(8).

    function g(a, f) {
        var b = [];
        for (var i = 0; i < a.length; i++) {
            b[i] = function(i){return function(){f(a[i])};}(i);
        }
        return b;
    }
    
  9. Write some JavaScript that adds a new method to arrays so that if I call this method on an array with two parameters f and g, I get back a new function which, when called with one argument k, returns the composition of f and g applied to the kth element of the original array. Hint: If we defined the functions square and addSix the obvious way, and we called this new method weird, then:
    [4, 6, 7, 3, 5, 2, 4].weird(addSix, square)
    
    would return the function z such that
    z(2) == 55
    
    because the element at index 2 within the array is 7 and $7^2 + 6 = 55$.
  10. In Go, Rust, Swift, C, and C++ arrays and records can be allocated on the stack, not just on the heap. When making assignments of aggregates to variables, compilers usually generate code to deposit the values in temporary storage. Why is this necessary in general? After all, in
    Weekdays := Day_Set(False, True, True, True, True, True, False);
    

    we could construct the aggregate directly in the variable Weekdays. Give an example of an assignment statement that illustrates the necessity of constructing an aggregate in temporary storage (before copying to the target variable).

  11. In Java, you generally implement callbacks via registration of listeners that implement a known interface, rather than using method pointers. Create a Swing component called AngleReader which displays a picture of a circle and notifies all its listeners of the angle, in degrees, that the mouse cursor makes with the horizontal axis of the circle as the mouse moves over it.
  12. Complete the following definition of a dot product function in ML:
    val dot =
        let
            fun transpose ... =
        in
            ....
        end;
    
    The transpose function should work like this
    transpose ([x1,...,xn],[y1,..,yn]) = [(x1,y1),...,(xn,yn)]
    
    raising Domain if the arrays have different lengths. The body of the definition of dot (between the in and end) should contain only instances of the functions transpose, o, foldr, map, op*, op+, and the value 0.
  13. Explain what is printed under (a) call by value, (b) call by value-result, (c) call by reference, (d) call by name.
    x = 1;
    y = [2, 3, 4];
    function f(a, b) {b++; a = x + 1;}
    f(y[x], x);
    print x, y[0], y[1], y[2];
    
    1. Under call by value, the arguments do not change; so the script prints 1 2 3 4.
    2. Under call by value/result, the increment of x does not take place until after the subroutine returns. It prints 2 2 2 4.
    3. Under call by reference, the increment of b changes x immediately, so the new value of x, namely 2, is used to update a, which is still y[1], and that becomes 2 + 1 = 3, so it prints 2 2 3 4.
    4. Under call by name, b++ changes x immediately so x becomes 2. Then, since a refers to the expression {y[x]}, it will need to compute y[2] which is 3. The script prints 2 2 3 3.
  14. Explain what is printed under (a) call by value, (b) call by value-result, (c) call by reference, (d) call by name.
    x = 1;
    y = 2;
    function f(a, b) {a = 3; print b, x;}
    f(x, x + y);
    print x;
    
    1. Value: 3 1 1
    2. Value-Result: 3 1 3
    3. Reference: 3 3 3
    4. Name: 5 3 3
  15. Using your favorite language and compiler, write a program that determines the order in which subroutine arguments are evaluated.
  16. Consider the following (erroneous) program in C:
    void f() {
        int i;
        printf("%d ", i++);
    }
    int main() {
        int j;
        for (j = 1; j <= 10; j++) f();
    }
    
    Local variable i in subroutine f is never initialized. On many systems, however, the program will display repeatable behavior, printing 0 1 2 3 4 5 6 7 8 9. Suggest an explanation. Also explain why the behavior on other systems might be different, or nondeterministic.
  17. Give an example which shows that default parameters are unnecessary in C++ because you can always get the desired effect with overloading.
  18. What does the following program output?
    with Ada.Text_IO, Ada.Integer_Text_IO;
    use Ada.Text_IO, Ada.Integer_Text_IO;
    
    procedure P is
      A: Integer := 4;
      type T is access Integer;
      B: T := new Integer'(4);
      C: T := new Integer'(4);
    
      procedure Q (X: in out Integer; Y: T; Z: in out T) is
      begin
        X := 5;
        Y.all := 5;
        Z.all := 5;
      end Q;
    
    begin
      Q (A, B, C);
      Put (A);
      Put (B.all);
      Put (C.all);
    end P;
    
  19. In some implementations of an old language called Fortran IV, the following code would print a 3. Can you suggest an explanation? (Hint: Fortran passes by reference.) More recent versions of the Fortran language don't have this problem. How can it be that two versions of the same language can give different results even though parameters are officially passed "the same way." Note that knowledge of Fortran is not required for this problem.
          call f(2)
          print* 2
          stop
          end
          subroutine f(x)
              x = x + 1
              return
          end
    

Modules, Classes, and Abstract Data Types

  1. Make a Perl module with a function called nextOdd. The first time you call this subroutine you get the value 1. The next time, you get a 3, then 5, then 7, and so on. Show a snippet of code that uses this subroutine from outside the module. Is it possible to make this module hack-proof? In other words, once you compile this module, can you be sure that malicious code can't do something to disrupt the sequence of values resulting from successive calls to this function?
  2. Consider the implementation of a Container class framework with the following abstract base class Container:
    template <class Item>
    class Container {
    public:
      unsigned numberOfItems() {return currentSize;}
      bool isEmpty() {return currentSize == 0;};
      virtual void flush() = 0;
      ~Container() {flush();}
    private:
      unsigned currentSize;
    };
    

    Here the idea is that each particular (derived) container class shall implement its own flush() operation (which makes sense because different containers are flushed in different ways: there may be arrays, linked lists, rings or hashtables used in the representation), and when a container is destroyed its flush() operation will be automatically invoked. However, the idea is flawed and the code as written causes a terrible thing to happen. What happens?

Object-Orientation

  1. What philosophers call a "class" mathematicians call a "set" (i.e., a collection of unordered, unique, values). So, a philosopher says that every member of a subclass is also a member of the superclass. But a C++ programmer says that every member of a superclass is also a member of its subclass! What is going on here?
  2. Write a three-page paper on the nature of identity in object oriented philosophy. Include some code fragments to illustrate your main points.
  3. It is certainly possible to make a Person class, then subclasses of Person for different jobs, like Manager, Employee, Student, Monitor, Advisor, Teacher, Officer and so on. But this is a bad idea, even though the IS-A test passes. Why is this a bad idea and how should this society of classes be built?
  4. One of the most important ways in which object oriented programming helps us to manage complexity is through the ability to group related classes into a hierarchy of subclasses and superclasses. Dynamic binding (run-time polymorphism) allows us to operate on collections of objects from different classes in a hierarchy safely. Furthermore, systems which are programmed using dynamic binding are more easily extendible.
    1. What construct is used in non-object oriented programming languages to simulate class hierarchies, and why do we say that it is unsafe?
    2. Why are inheritance-like structures in non-OOPLs harder to extend?
  5. Why is it said that implementation inheritance is at odds with encapsulation?
  6. Inheritance is not always appropriate. Discuss the reasons why a design with a superclass Person and subclasses for different jobs (e.g., programmer, manager, ticket agent, flight attendant, supervisor, student, etc.) is a lousy design. Give an alternative.
  7. In designing a class hierarchy in C++, when should you make an operation virtual and when should you make an operation non-virtual? Give examples.
  8. Write a Perl "class" for machine parts that have an identification number (a positive integer divisible by 5), a weight (a positive floating-point number) and a name (which must consist entirely and exclusively of alphabetic characters). Provide a "constructor" that takes in a string consisting of the id, weight, and name, respectively in which
    • the string may have leading and trailing spaces
    • the three fields are separated by a vertical bar
    • the weight is not expressed in scientific notation: it can have an integral value, but if it does have a decimal point, then it is followed by a non-empty fractional part. There is no "E" part, ever. It's simple.
    The constructor will check for a valid argument by matching against a regex, and if all is cool, will split the string to assign to its fields.
  9. Find some old "procedural" code you have written and rewrite in an object-oriented fashion. I don't mean that you have to use inheritance or polymorphism; all I am really looking for is that you wrap some functions up in a sensible class.
  10. A common pattern that comes up a lot is the need to assign unique identifiers to objects of a given class, for example:
    class Item {
        private int id;
        private static int numberOfItemsCreated = 0;
        public Item() {id = numberOfItemsCreated++;}
        // pretend that there are more members here...
    };
    
    As you can see, every item that gets created will get a unique id. Because this pattern occurs frequently, it might be nice to generalize this and make make something reusable out of it so we don't have to write this code inside every class that needs ids. Perhaps we need an interface or abstract class. Tell me why these two suggestions won't work with a detailed, technical answer. Then tell me something that will work. (Note: there is nothing wrong with the access modifiers above; the problems with my two suggestions have to do with the nature of interfaces and abstract classes.)
  11. Given a utility class, can you always rewrite it as a singleton? Given a singleton, can you always rewrite it as a utility class? If so, when would you choose one over the other?
  12. Explain how, in C++, you can get access to, and indeed modify, a protected component of an object that someone else declared. As a concrete example, let's say someone has declared
        class C {protected: int x; ...};
        C c;
    

    then your job is to assign a new value to c.x. Assume there are no public operations of C that modify x that you know of. Also, do not use any preprocessor tricks (like #define protected public).

  13. What makes more sense, to inherit a list from a stack or a stack from a list?
  14. Why did the designers of the C++ standard library containers emphatically reject an inheritance hierarchy of containers?
  15. In C++ you can write
    class C {int x;};
    C c;
    C* p = &c;
    cout << p;
    
    and there is no compile-time nor link time error, despite the fact that operator<<(C*) is not a member of ostream (since that class was declared before you declared C), nor for that matter did anyone declare the global function
        ostream& operator<<(ostream&, C*);
    
    So why does it all work? Explain exactly what gets printed and why.
  16. What happens to the implementation of a class if we "redefine" a field in a subclass? For example, suppose we have:
    class Foo {
        public int a;
        public String b;
    }
    ...
    class Bar extends Foo {
        public float c;
        public int b;
    }
    
    Does the representation of a Bar object contain one b field or two? If two, are both accessible, or only one? Under what circumstances? Answer for C++, Java, Python, and Scala.
  17. If Foo is an abstract class in a C++ program, why is it acceptable to declare variables of type Foo*, but not of type Foo? Does this problem even make sense to ask in Java or Python?

Concurrency

  1. Implement a priority queue data type in Ada, using a server task to provide synchronization.
  2. Implement a priority queue data type in Ada, where each priority queue object is a protected object.
  3. In the example Ada package implementing the Set data type with a guardian task, there is a serious problem with the package design: errors in insertion are not handled well! What happens if we run out of memory? (Answer in terms of the system interfaces.) Show how to add robust error handling to the package and comment on the amount of parallelism permitted with your solution.
  4. Discuss the difficulties of implementing a secure Post Office object in Ada that meets the following requirements. The post office is to maintain a collection of P.O. boxes, each belonging to some task. Any task can put a letter into another task's box, but only the owner of a particular box can open it and read the letters.
  5. A relay is an agent task created by one task to relay a message to another. For example, if a calling task wishes to send a message to another but does not wish to wait for a rendezvous, the caller can create a relay task to send the message. (Note that relays are only appropriate to use when there are no out parameters in the called entry.) Sketch in detail a body for an Ada task T that uses a relay R to call entry E of task U, passing message X.
  6. In Ada, if two tasks are executing a Put procedure at the same time, their outputs may be interleaved. (This could produce amusing and even distasteful results, e.g. writing "sole" in parallel with "ash") Show how to set things up so only one task is writing at a time.
  7. Why do Java programmers not have to worry about the situation in the previous problem (interleaving of text output written to a stream)?
  8. One of the nice features of Quicksort is that it allows a great deal of parallelism in an implementation. After partitioning, the slices on either side of the pivot can be sorted in parallel. It is very easy to set things up to do this in languages such as occam, but tedious in Ada and Java. Code up a parallel version of Quicksort in Ada or Java and explain why it is messy.
  9. In Ada, what happens when you try to call an entry in a task that has terminated? Comment on the following code fragment as a possible approach to calling entry E of task T only if T has not terminated.
    if not T'Terminated then
        T.E;
    end if;
    
  10. In Java, what happens if you invoke a method on a thread that has completed?
  11. Here's an open-ended question many students hate, especially on exams. Two JavaScript programmers are arguing over the best way to implement a little timer widget. The first programmer prefers:
    let countDown = function () {
        let i = 10;
        let update = function () {
            document.getElementById("t").innerHTML = i;
            if (i-- > 0) setTimeout(update, 1000);
        }
        update();
    }
    
    The second argues that this is better:
    let countDown = function () {
        let update = function (i) {
            document.getElementById("t").innerHTML = i;
            if (i-- > 0) setTimeout(function () {update(i)}, 1000);
        }
        update(10);
    }
    
    Your role is to figure out which programmer is right, if any. Make a fairly extensive list of the pros and cons of each approach. Your list will be graded on completeness, neatness, correct usage of terminology (don't forget to mention "anonymous function" and "closure"), and how articulately you express yourself. Bad grammar will impact your grade negatively. You may want to consider readability and (especially) performance.