繁体   English   中英

在 Rego 语言中比较两个 arrays

[英]Compare two arrays in the Rego Language

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

    msg := sprintf("")
}

我想比较所需数组中输入数组中的每个值。 在其他语言中,两个正常的循环会做到这一点。 但在 Rego 语言中,它们不是循环。 有谁知道我该怎么做

colorSetrequiredSet变量显示了如何将数组转换为集合。

使用==运算符,我们可以确定是否所有 colors 都存在

package play

default allColorPresent = false

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

有关如何迭代集合的信息,请参阅有关迭代的文档部分。 然而,使用集合通常更惯用。 按照你的例子:

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]")
}

有很多方法可以做到:

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