10. Collecting solutions

Until now, each answer came one by one, and you pressed Next answer for the next one. Often you want all the answers at once, in a list, to count them, sort them, or use them in the next step. This chapter is the last one before the first goal, the Game of Life.

findall

findall(Template, Goal, List) finds every answer of Goal, and makes a list of Template for each one.

The template can be any term, such as the pair A-B. If there is no answer, the list is empty, and findall/3 still succeeds.

findall/3 is like Array.prototype.map and filter together, but it works on answers instead of an array.

Remove duplicates with sort

sort/2 sorts a list and removes duplicates. Use it after findall/3 when the same answer can come more than once.

msort/2 sorts without removing duplicates. Both use the standard order of terms, where numbers come before atoms, and atoms are in alphabetical order.

bagof and setof

bagof/3 is like findall/3, but it groups the answers by the other variables of the goal. setof/3 also sorts each group and removes duplicates.

The first query gives one answer for each age, with the names of that age. Age is not in the template Name, so bagof/3 makes a group for each value of Age. In the second query, the template Age-Name has both variables, so nothing is left to group by, and setof/3 gives all the pairs in one sorted list. Unlike findall/3, bagof/3 and setof/3 fail when there is no answer.

forall

forall(Condition, Action) is true when Action is true for every answer of Condition. It is useful in two ways.

To check something for all answers.

== checks that two terms are already the same. Unlike =, it never gives a value to a variable. If L had no value, L == mit would simply fail.

And to print something for each answer.

write/1 prints a term, and nl/0 starts a new line. The output appears in the box above the answer.

Loops over numbers

between/3 with forall/2 works like a for loop. This draws a small square. You will use the same idea to draw the board of the Game of Life.

Try it

  1. Count the packages that my_app needs, without duplicates.
  2. Print each package and the number of packages it depends on directly. You can use forall/2 and findall/3 together.
An unhandled error has occurred. Reload 🗙