class Foo {
final bool a;
final bool b;
final bool c;
final bool d;
Foo({
this.a = false,
this.b = false,
this.c = false,
this.d = false,
}) : assert(a ^ b ^ c ^ d, 'Only one of them can be true.');
}
我想確保只有一個屬性a,b和can 。我試過了,但它不適用于這種情況。cdtruea ^ b ^ c ^ d
注意:我不是在尋找冗長的方式,即(a && !b && !c && !d) || (!a && b && !c && !d) ...
uj5u.com熱心網友回復:
一種通用技術是將布林值放入 a 中List,然后計算true元素的數量。這也將允許您檢查某個數字是否正確,至少某個數字是否正確,或者至多某個數字是否正確。
以下是實作該功能的幾種方法:
extension CountExtension<T> on Iterable<T> {
/// Returns a count of the elements in `this` that are equal to [value].
int countOf(T value) => fold<int>(0, ((sum, e) => sum ((e == value) ? 1 : 0)));
}
T identity<T>(T object) => object;
void main() {
var booleans = [true, false, true, false];
print(booleans.countOf(true)); // Prints: 2
print(booleans.where(identity).length); // Prints: 2
}
并應用于您的示例:
class Foo {
final bool a;
final bool b;
final bool c;
final bool d;
Foo({
this.a = false,
this.b = false,
this.c = false,
this.d = false,
}) {
assert([a, b, c, d].countOf(true) == 1, 'Exactly one must be true');
// Or alternatively:
assert(
[a, b, c, d].where(identity).length == 1,
'Exactly one must be true',
);
}
}
(我希望countOf在某個地方的某個公共包中已經存在等效的東西,但我目前似乎找不到。)
uj5u.com熱心網友回復:
由于您想要在建構式中使用它assert,我假設您還想要一個常量運算式(因為否則[a, b, c, d].where((x)=>x).length == 1會這樣做,如@jamesdlin 所示)。
僅使用基本布爾運算子我能想到的最短的是
assert((a || b || c || d) &&
!(a && b || a && c || a && d || b && c || b && d || c && d))
不是很好,變數數量呈二次方。
使用?/:可以使它更小:
assert(a ? !(b || c || d) : b ? !(c || d) : c ^ d)
也是二次的,只是具有(顯著!)較小的常數因子。
如果您查看布爾函式的必要二元決策圖(如二元決策樹,只是它是 DAG),它實際上是線性的,因此這表明您可以僅使用布爾運算子制作線性運算式,但它是通過共享子樹,這意味著您需要更復雜的控制流或區域變數。使用let建構式,您可以執行以下操作:
let cd1 = c ^ d,
ncd = !c && !d,
bcd1 = b ? ncd : cd1,
nbcd = !b && ncd
in a ? nbcd : bcd1
它可以擴展到任意數量的變數中的線性運算式(因為ncd這里的共享,它變得更加共享更多的變數)。它實際上與上面的?/:版本相同,共享相同的子運算式。遺憾的是,Dart 沒有let可以在 中使用的構造assert,所以這只是理論上的樂趣。
所以,我也會使用算術運算,因為你在數:
assert((a ? 1 : 0) (b ? 1 : 0) (c ? 1 : 0) (d ? 1 : 0) == 1)
const該運算式在建構式中簡單、線性且有效assert。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/464481.html
標籤:镖
上一篇:如何使影像隨機生成器顫動?
下一篇:顫動下拉按鈕選擇問題
