Contents
Comprehensions build composite values from inner queries — object, array, or set — in one expression. The official definition is dry; examples stick better.
We’ll aggregate a list of file paths in different ways.
1 | // input.json |
Comprehensions
Syntax recap: { key: value | body }, [ value | body ], { value | body } (set).
Object comprehensions
Group paths by type:
1 | import input.files |
Outer loop binds type; inner comprehension collects matching paths.
1 | opa eval -f values -d . -i input.json "data.example_comprehensions.group_files_by_type" |
Form: { <key>: <term> | <body> }. Every conjunct in <body> must succeed.
Array comprehensions
paths above is an array comprehension: [ <term> | <body> ].
Arrays use [] and allow duplicates.
Normalize everything to posix-style paths:
1 | convert_all_to_posix_path_array := [path | |
Inner comprehensions filter by file.type; array.concat merges.
Set comprehensions
Same idea, set form — no duplicates:
1 | convert_all_to_posix_path_sets := {path | |
Syntax: { <term> | <body> }. Union |, intersection &, difference -.
Once the shapes feel familiar, a lot of aggregation code shrinks to one comprehension.
Exercise
Group by file extension. Target shape:
1 | { |
Hints — hard-code extensions:
extSets := ["yaml", "yml", "json"]
Or regex:
1 | extSets := {e | |
Answers in opa-koans.
Next: tests, profiling, and benchmarks.
Code: comprehensions.rego
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
