我想写一个函数,比如:

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

有效但不优雅我在寻找更优雅的解决方案。

最佳答案

使用all

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

使用nub来自Data.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是否有不属于Eq实例的类型。

09-05 05:24