2016-11-26 88 views
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 

有效虽不精致。我正在寻找一些更优雅的解决方案。

回答

7

随着all

sameBool :: [Bool] -> Bool 
sameBool xs = all (== head xs) xs 

随着nubData.List

import Data.List 

sameBool :: [Bool] -> Bool 
sameBool = (== 1) . length . nub 

其实,他们的作品为Eq任何实例:

sameBool :: Eq a => [a] -> Bool 
sameBool xs = all (== head xs) xs 
-- Note: return True for [] 

sameBool :: Eq a => [a] -> Bool 
sameBool = (== 1) . length . nub 
-- Note: return False for [] 

检查nubBy为大家还不类型t的情况Eq

+3

而不是'(== 1)。长度'我会使用'null。下降1“,因为它更懒惰。这就是说,如果它已经找到了“真”和“假”的话,它并不需要遍历整个列表。请注意,此更改也会为'[]'返回'True'而不是'False',这可能会或可能不需要。 – jpath

+3

哇。其中'head xs'不会在空列表中出错的罕见情况之一。我花了几秒钟才意识到这确实是安全的:-) – chi

+0

@jpath他自己的代码在空列表上触发异常 – Wentao

相关问题