Picat Imperative Programming Constructs 2 — Questions and Answers
Question 1: Which operator is used for destructive assignment in Picat's imperative mode?
- =
- := (Correct answer)
- <-
- ==
Correct answer: :=
In Picat's imperative mode, := performs destructive (mutable) assignment, unlike = which is unification.
Question 2: What does the `foreach` loop in Picat use to iterate over a list?
- foreach(X in List) do ... end (Correct answer)
- foreach X in List ... end
- for X in List do ... end
- loop X in List do ... end
Correct answer: foreach(X in List) do ... end
Picat's foreach loop uses the syntax `foreach(X in List) do ... end` to iterate over elements.
Question 3: In Picat, what happens when a `while` loop condition becomes false?
- An exception is raised
- The loop body executes one final time
- The loop terminates and execution continues after `end` (Correct answer)
- The program halts
Correct answer: The loop terminates and execution continues after `end`
When the while loop condition is false, the loop exits and control passes to the statement after the end keyword.
Question 4: How do you declare a local variable inside a Picat imperative function?
- var X
- local X
- X = _
- No declaration needed; first assignment creates it (Correct answer)
Correct answer: No declaration needed; first assignment creates it
In Picat, variables do not need explicit declarations; the first assignment in a scope implicitly introduces them.
Question 5: Which Picat construct provides a `do ... while` style loop that tests the condition at the end?
- repeat ... until Cond end
- do ... while Cond end
- loop ... end Cond
- Picat has no post-condition loop construct (Correct answer)
Correct answer: Picat has no post-condition loop construct
Picat does not have a built-in do-while construct; programmers simulate post-condition loops with while or recursion.
Question 6: In Picat, what is the result of executing `X := 5, X := X + 1`?
- X is bound to 5 permanently via unification
- X becomes 6 (Correct answer)
- A runtime error is thrown because X is already bound
- X becomes 5+1 as an unevaluated term
Correct answer: X becomes 6
The := operator allows reassignment, so X is first set to 5 and then updated to 6.
Question 7: What is the correct way to break out of a `foreach` loop early in Picat?
- Use the `break` keyword inside the loop
- Throw and catch an exception
- Use a boolean flag variable with a while loop instead (Correct answer)
- Call `halt`
Correct answer: Use a boolean flag variable with a while loop instead
Picat's foreach does not support break; the idiomatic workaround is to use a while loop with a flag or a recursive helper.
Which operator is used for destructive assignment in Picat's imperative mode?