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.

check-basic.cue

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":
    ./check-basic.cue:3:5
    ./check-basic.cue:4:2
    ./check-basic.cue:4:13
    ./check-basic.cue:11:10
    ./check-basic.cue:11:15
    ./check-basic.cue:11:17
    ./check-basic.cue:11:38

This example works for a list of structs.

check-struct.cue

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

#X: {
	for x in X {
		"\(x.name)": 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.
2024 Hofstadter, Inc