Picat Imperative Programming Constructs 4 — Questions and Answers
Question 1: In Picat, what is the scope of a variable assigned inside a `foreach` loop body?
- It is local to each loop iteration only
- It is visible in the enclosing function after the loop ends (Correct answer)
- It is global across all functions
- Variables cannot be assigned inside foreach bodies
Correct answer: It is visible in the enclosing function after the loop ends
Variables assigned inside a foreach loop body are visible in the surrounding function scope after the loop completes.
Question 2: Which operator tests value equality (not unification) in Picat's imperative code?
- =
- == (Correct answer)
- =:=
- is
Correct answer: ==
The == operator tests structural/value equality without binding variables, while = performs unification.
Question 3: What is the Picat equivalent of a C-style `for(i=0; i<n; i++)` loop?
- foreach(I in 0..n-1) (Correct answer)
- for I := 0 to n-1 do ... end
- loop I from 0 to n-1 do ... end
- while I < n do I := I + 1 end
Correct answer: foreach(I in 0..n-1)
Picat uses `foreach(I in 0..n-1)` to iterate over a range, equivalent to C's for loop from 0 to n-1.
Question 4: In Picat, what does the `!` (cut) operator do in an imperative clause?
- It forces immediate evaluation of an expression
- It commits to the current clause, pruning remaining alternatives (Correct answer)
- It is the boolean NOT operator
- It exits the current loop iteration
Correct answer: It commits to the current clause, pruning remaining alternatives
The cut (!) in Picat, inherited from Prolog, commits to the current clause and eliminates remaining choice points.
Question 5: How does Picat handle an `if` condition that raises an exception during evaluation?
- The else branch executes automatically
- The exception propagates up the call stack (Correct answer)
- The condition is treated as false
- The if statement is silently skipped
Correct answer: The exception propagates up the call stack
Uncaught exceptions in an if condition propagate normally up the call stack just as they would in any other position.
Question 6: What is the syntax to read an integer from standard input in Picat?
- X := read_int() (Correct answer)
- X = read_int()
- X := read_term()
- read(X, int)
Correct answer: X := read_int()
Picat provides read_int() as a built-in function; the result is assigned with := in imperative mode.
Question 7: In a Picat function, what happens if execution reaches the end of the body without a `return`?
- The function returns the last evaluated expression (Correct answer)
- An error is raised
- The function implicitly returns true
- The function returns a free (unbound) variable
Correct answer: The function returns the last evaluated expression
In Picat, if no explicit return is reached, the value of the last expression in the function body is returned.
In Picat, what is the scope of a variable assigned inside a `foreach` loop body?