3
我想编写一个函数,如:如何检查一个Bool值列表是否包含相同的值?
sameBool :: [Bool] -> Bool
例如:
[True, False, True] => False
[True, True] => True
这里是我的解决方案:
sameBool :: [Bool] -> Bool
sameBool xs = if head xs == True
then length (filter (== False) xs) == 0
else length (filter (== True) xs) == 0
有效虽不精致。我正在寻找一些更优雅的解决方案。
而不是'(== 1)。长度'我会使用'null。下降1“,因为它更懒惰。这就是说,如果它已经找到了“真”和“假”的话,它并不需要遍历整个列表。请注意,此更改也会为'[]'返回'True'而不是'False',这可能会或可能不需要。 – jpath
哇。其中'head xs'不会在空列表中出错的罕见情况之一。我花了几秒钟才意识到这确实是安全的:-) – chi
@jpath他自己的代码在空列表上触发异常 – Wentao