【问题标题】:Why does `and` return True for empty foldable but `or` return False in Haskell? [duplicate]为什么`and`对于空的可折叠返回True,但`or`在Haskell中返回False? [复制]
【发布时间】:2018-12-22 21:59:05
【问题描述】:

是否有理由解释这样的结果是否符合预期?它们比未定义更好吗?

>>> 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

【问题讨论】:

  • 好吧and 基本上是为所有元素制作fold&&,但最初需要True(因为否则结果总是False,无论值如何) .
  • 这是跨语言的标准处理。例如,here's the same question in Java。这个概念被称为“空洞的真相”。
  • 请注意,出于同样的原因,sum [] == 0product [] == 1

标签: haskell


【解决方案1】:

为了扩展 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-02-08
      • 1970-01-01
      • 2015-06-22
      • 2021-11-10
      • 1970-01-01
      • 2021-07-02
      • 2011-05-22
      • 1970-01-01
      • 2014-07-03
      相关资源
      最近更新 更多