为什么`和`为空可折叠返回True,但`或`在Haskell中返回False? [重复]

问题描述 投票:4回答:2

这个问题在这里已有答案:

是否有理由可以解释这些结果是否可以预期?它们比未定义更好吗?

>>> any (const True) []
False

>>> any (const False) []
False

>>> or []
False

>>> and []
True

我真的不明白报告试图说的是什么:

-- and returns the conjunction of a Boolean list. For the result to be
-- True, the list must be finite; False, however, results from a False
-- value at a finite index of a finite or infinite list. or is the
-- disjunctive dual of and. 
and, or     :: [Bool]    -> Bool
and         =  foldr    (&&)    True
or          =  foldr    (||)    False
haskell
2个回答
8
投票

为了扩展Dan的答案,真值的空列表的结合是真的True允许你扩展连接的预期属性到那种情况。

例如,我们希望如此,

and (xs ++ ys) = (and xs) && (and ys) 

对于我们所有的xsxs = xs ++ []所以,

  and xs 
= and (xs ++ [])
= (and xs) && (and []) 

考虑到and xs可能是TrueFalse它遵循,

True  = True  && (and [])
False = False && (and [])

因此,我们必须有and []True


7
投票

大多数具有类似功能的语言都是如此。这是因为“真”是“&&”的标识(意思是x && True == x)。同样,“假”是“||”的标识(意思是x || False == x)。

© www.soinside.com 2019 - 2024. All rights reserved.