我想写一个像:
这样的函数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
有效但不优雅。我正在寻找更优雅的解决方案。
答案 0 :(得分:7)
使用all:
sameBool :: [Bool] -> Bool
sameBool xs = all (== head xs) xs
来自Data.List
的{{3}}:
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 []
检查nub是否有Eq
的实例。