1
votes

I'm writing a function that compares two vectors in haskell using comprehension lists. The thing is that I want to add booleans to my final list, but Haskell interprets this code as if x == y, add the element to the list (that's how comprehensive lists works I know). What I want is a list with booleans if the coordinates I'm comparing are true or false. Is it possible to do this with comprehension lists?

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

PD: I'm going to use foldr (&&) True with the list that returns igualdad, in order to get the final result that I want. Thanks.

1
THis will return a list of Bools. I'm not really sure what is not working. For two vectors of length m and n, it will generate a list with mn elements. - Willem Van Onsem
Nop, It is only adding items to the lists when x == y and I need it to add false to the list when x /= y - moliverac8
that is the case here. You can inspect that. It would only add Trues if you wrote [x == y | x <- xs, y <- ys, x == y] (so with a condition at the right end). - Willem Van Onsem
@milverac8: are you sure your vectors contain something else than one value, and are you sure vectorToFloatList works correctly. - Willem Van Onsem

1 Answers

1
votes

What I want is a list with booleans if the coordinates I'm comparing are True or False. Is it possible to do this with comprehension lists?

You get such a list. For two Vectors v and w with lengths m and n respectively, you will get a list with m×n elements, such that the item vi and wj will be compared in the result list in the element with index i×m + j.

If you hwever want a list of length min(m, n), such that the item at index i checks if vi and wi are the same, then we can make use of zip :: [a] -> [b] -> [(a, b)]:

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

or with zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] and on :: (b -> b -> c) -> (a -> b) -> a -> a -> c:

import Data.Function(on)

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

or we can make use of the ParallelListComp extension [ghc-doc] and run this with:

{-# LANGUAGE ParallelListComp #-}

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

PD: I'm going to use foldr (&&) True with the list that returns igualdad.

There exists a function for that already: that is and :: Foldable f => f Bool -> Bool. If you however want to check if all the items are the same, you can just use all :: Foldable f => (a -> Bool) -> f a -> Bool here:

import Data.Function(on)

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