【问题标题】:Haskell and comprehension listsHaskell 和理解列表
【发布时间】:2019-10-13 16:43:03
【问题描述】:

我正在编写一个函数,它使用理解列表比较 haskell 中的两个向量。问题是我想将布尔值添加到我的最终列表中,但是 Haskell 将此代码解释为好像 x == y,将元素添加到列表中(这就是我所知道的综合列表的工作方式)。如果我要比较的坐标是真还是假,我想要的是一个带有布尔值的列表。 可以用理解列表来做到这一点吗?

igualdad :: Vector -> Vector -> [Bool]
igualdad v1 v2 = [ x == y | x <- xs, y <- ys]
    where xs = vectorToFloatList v1
          ys = vectorToFloatList v2

PD:我将使用 foldr (&&) True 和返回 igualdad 的列表,以获得我想要的最终结果。 谢谢。

【问题讨论】:

  • 这将返回Bools 的列表。我不确定什么不起作用。对于长度为 mn 的两个向量,它将生成一个包含 mn 个元素的列表。
  • 不,它只是在 x == y 时将项目添加到列表中,我需要它在 x /= y 时将 false 添加到列表中
  • 这里就是这样。你可以检查一下。如果你写了[x == y | x &lt;- xs, y &lt;- ys, x == y],它只会添加Trues(所以在右端有一个条件)。
  • @milverac8:你确定你的向量包含的不是一个值吗,你确定vectorToFloatList 工作正常吗?

标签: haskell


【解决方案1】:

如果我要比较的坐标是TrueFalse,我想要的是一个带有布尔值的列表。是否可以使用理解列表来做到这一点?

你会得到这样一个列表。对于长度分别为 mn 的两个 Vectors vw,您将获得一个列表m×n 个元素,这样项目 viwj 将在结果列表中比较索引为i×m + j的元素。

如果你想要一个长度为 min(m, n) 的列表,那么索引 i 处的项目会检查 viwi 是一样的,那么我们可以使用zip :: [a] -&gt; [b] -&gt; [(a, b)]:

igualdad :: Vector -> Vector -> [Bool]
igualdad v1 v2 = [ x == y | (x, y) <- zip (vectorToFloatList xs) (vectorToFloatList ys)]

或使用zipWith :: (a -&gt; b -&gt; c) -&gt; [a] -&gt; [b] -&gt; [c]on :: (b -&gt; b -&gt; c) -&gt; (a -&gt; b) -&gt; a -&gt; a -&gt; c

import Data.Function(on)

igualdad :: Vector -> Vector -> [Bool]
igualdad = on (zipWith (==)) vectorToFloatList

或者我们可以使用ParallelListComp extension [ghc-doc] 并运行它:

{-# LANGUAGE ParallelListComp #-}

igualdad :: Vector -> Vector -> [Bool]
igualdad v1 v2 = [ x == y | x <- vectorToFloatList xs | y <- vectorToFloatList ys]

PD:我将在返回 igualdad 的列表中使用 foldr (&amp;&amp;) True

已经存在一个函数:即and :: Foldable f =&gt; f Bool -&gt; Bool。但是,如果您想检查所有项目是否相同,您可以在这里使用all :: Foldable f =&gt; (a -&gt; Bool) -&gt; f a -&gt; Bool

import Data.Function(on)

sameVec :: Vector -> Vector -> Bool
sameVec = on (all (uncurry (==) .) . zip) vectorToFloatList

【讨论】:

    猜你喜欢
    • 2021-01-12
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多