Required List Element

The Required List Element pattern enables us to verify elements without knowing their position.

This example works for basic types like ints and strings.


X: [1, 2, 4]

#X: {
	for x in X {
		"\(x)": x

#MustHave: [3]

#Xcheck: #X & {for x in #MustHave {"\(x)": x}}

cue eval check-basic.cue

#Xcheck: field not allowed: "3":

This example works for a list of structs.


X: [{
	name: "a"
	val:  1
}, {
	name: "b"
	val:  2
}, {
	name: "c"
	val:  3

#X: {
	for x in X {
		"\(": x

#MustHave: ["b"]

#Xcheck: #X & {for x in #MustHave {"\(x)": _}}

If you want to check that structs have a specific pattern, you can replace the _ with a definition. Even better would be to apply the definition to the original list.

Some considerations:

  • You will need the elements to have a unique key. You could use true or any (_) as the value if you don’t care about duplicate keys with different values.
  • This pattern will change once Associative Lists are implemented.
We'll never share your email with anyone else.
2023 Hofstadter, Inc