Picat Pattern Matching Rules 2 — Questions and Answers
Question 1: In Picat, what does the `?=>` operator signify in a rule head compared to `=>`?
- `?=>` is non-deterministic (allows backtracking); `=>` is deterministic (commits on match) (Correct answer)
- `?=>` matches only atoms; `=>` matches compound terms
- `?=>` requires a guard; `=>` does not
- `?=>` is used for predicates only; `=>` is for functions only
Correct answer: `?=>` is non-deterministic (allows backtracking); `=>` is deterministic (commits on match)
Rules using `?=>` are non-deterministic and allow the system to backtrack and try other clauses, while `=>` commits to the first matching clause.
Question 2: Which Picat pattern correctly matches a list with exactly two elements?
- [X, Y] (Correct answer)
- [X | Y]
- [X, Y | _]
- [X | [Y | []]]
Correct answer: [X, Y]
`[X, Y]` matches a list of exactly two elements, binding X to the first and Y to the second.
Question 3: In a Picat rule, a guard expression appears:
- After the rule head, preceded by a comma, before the neck operator (Correct answer)
- Inside the rule body after `:-`
- As the last statement in the rule body
- Inside brackets following the predicate name
Correct answer: After the rule head, preceded by a comma, before the neck operator
A guard is a condition placed after the pattern head and before the `=>` or `?=>` neck, separated by a comma.
Question 4: What happens when no pattern in a Picat function definition matches the given arguments?
- A runtime exception is thrown (Correct answer)
- The function returns `none`
- The last clause always matches as a fallback
- The program silently succeeds
Correct answer: A runtime exception is thrown
If no clause pattern matches the arguments, Picat throws an existence error or no-clause exception at runtime.
Question 5: Which pattern in Picat uses an anonymous variable to ignore a list element?
- [_, X | _] (Correct answer)
- [nil, X | nil]
- [*, X | *]
- [any, X | any]
Correct answer: [_, X | _]
The underscore `_` is Picat's anonymous variable that matches any value without binding it.
Question 6: Consider `foo([H|T]) => write(H).` — what does H bind to when called as `foo([1,2,3])`?
- 1 (Correct answer)
- [1,2,3]
- [2,3]
- The entire list
Correct answer: 1
In the head pattern `[H|T]`, H binds to the first element (head) of the list, which is 1.
Question 7: In Picat pattern matching, what does matching against an integer literal in the head accomplish?
- It restricts the rule to fire only when the argument equals that exact integer (Correct answer)
- It converts the argument to an integer
- It matches any numeric value
- It always fails at compile time
Correct answer: It restricts the rule to fire only when the argument equals that exact integer
A literal in a pattern head acts as an equality constraint, so the rule only fires if the argument unifies with that exact value.
In Picat, what does the `?=>` operator signify in a rule head compared to `=>`?