简体   繁体   English

在 Rego 语言中比较两个 arrays

[英]Compare two arrays in the Rego Language

violation[{"msg": msg}] {
    required:= ["red", "green", "blue"]
    input := ["orange", "purple"]

    msg := sprintf("")
}

I want to compare each value from the input array in the required array.我想比较所需数组中输入数组中的每个值。 In other languages, two normal loops will do it.在其他语言中,两个正常的循环会做到这一点。 but in the Rego language, they are no loops.但在 Rego 语言中,它们不是循环。 Does anybody know how can I do it有谁知道我该怎么做

colorSet and requiredSet variable shows how to convert array to set. colorSetrequiredSet变量显示了如何将数组转换为集合。

Using == operator we can figure out if all colors are present or not使用==运算符,我们可以确定是否所有 colors 都存在

package play

default allColorPresent = false

allColorPresent  {
   colorSet := {x | x := input.colors[_]} 
   requiredSet := {x | x := input. required[_]}
   colorSet == requiredSet
}

See the docs section on iteration for how to iterate over a collection.有关如何迭代集合的信息,请参阅有关迭代的文档部分。 It is however often more idiomatic to work with sets.然而,使用集合通常更惯用。 Following your example:按照你的例子:

violation[{"msg": msg}] {
    required := {"red", "green", "blue"}
    input.colors := {"orange", "purple"}
    
    count(required - input.colors) != 0

    msg := sprintf("input.colors (%v) does not contain all required colors (%v), [input.colors, required]")
}

There are many ways to do it:有很多方法可以做到:

import future.keywords.in

violation[{"msg": msg}] {
    required:= ["red", "green", "blue"]
    input_colors := ["orange", "purple", "blue"]
    
    wrong_colors := [ color | color := input_colors[_]; not (color in cast_set(required)) ]
    count(wrong_colors) > 0
    msg := sprintf("(%v) not in required colors (%v)", [wrong_colors, required])
}
import future.keywords.in
import future.keywords.every

all_colors_present(input_colors, required_colours) {
    every color in input_colors {
        color in cast_set(required_colours)
    }
}

violation[{"msg": msg}] {
    required:= ["red", "green", "blue"]
    input_colors := ["r", "green", "blue"]
    
    not all_colors_present(input_colors, required)
    msg := "not all colors present!"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM