Picat Imperative Programming Constructs 5 — Questions and Answers
Question 1: Which Picat construct is used to handle runtime exceptions in imperative code?
- try ... catch ... end (Correct answer)
- begin ... rescue ... end
- catch(Goal, Error, Handler)
- on_error(Goal, Handler)
Correct answer: try ... catch ... end
Picat uses try ... catch(Pattern) ... end blocks to intercept and handle exceptions.
Question 2: What does `string_to_atom(S)` do when used in a Picat imperative function?
- Converts an atom to a string
- Converts a string (char list) to an atom (Correct answer)
- Parses a string as a Picat term
- Splits a string into individual characters
Correct answer: Converts a string (char list) to an atom
string_to_atom/1 converts a Picat string (list of character codes or chars) into an atom.
Question 3: How do you concatenate two lists in Picat within an imperative function?
- L1 ++ L2 (Correct answer)
- append(L1, L2)
- L1 + L2
- concat(L1, L2)
Correct answer: L1 ++ L2
The ++ operator performs list concatenation in Picat, returning a new combined list.
Question 4: In Picat's imperative mode, what does `X @= Y` mean?
- X is unified with Y using occurs check
- X is assigned the value of Y only if X is unbound (Correct answer)
- X is element-wise equal to array Y
- There is no @= operator in Picat
Correct answer: X is assigned the value of Y only if X is unbound
The @= operator in Picat assigns Y to X only when X is an unbound (free) variable, leaving it unchanged otherwise.
Question 5: What is the output of the Picat code: `X := 3, (X > 2 -> Y := "big" ; Y := "small"), print(Y)`?
- big (Correct answer)
- small
- A runtime error
- true
Correct answer: big
Since X is 3 which is greater than 2, the then-branch executes and Y is assigned "big", which is then printed.
Question 6: In Picat, which of the following correctly swaps the values of two mutable variables A and B?
- A := B, B := A
- swap(A, B)
- Tmp := A, A := B, B := Tmp (Correct answer)
- A <=> B
Correct answer: Tmp := A, A := B, B := Tmp
A temporary variable must hold one value during the swap; the naive two-step assignment would lose A's original value.
Question 7: What does a `foreach` loop do when given an empty list in Picat?
- Raises an empty_list exception
- Executes the body once with an unbound variable
- Skips the body entirely and continues normally (Correct answer)
- Causes an infinite loop
Correct answer: Skips the body entirely and continues normally
Iterating over an empty list with foreach simply skips the loop body; this is the standard and expected behavior.
Which Picat construct is used to handle runtime exceptions in imperative code?