1

I got a tuple with Either values in it,

(Left "Error1", Right 1, Left "Error2", Right 2) 

How can i convert this to

[Left "Error1", Right 1, Left "Error2", Right 2]

?

Since I want to do lefts on the list and get all Left values from

[Left "Error1", Right 1, Left "Error2", Right 2]

I have something like this with 38 values in the tuple, (Left "Error1", Right 1, Left "Error2", Right "NameString") is it possible to get only the left values from the tuple?

3 Answers3

8

This question has nothing to do with Either – you could as well ask how to convert a tuple of characters into a list of characters.

The answer is: there is no standard method for doing this, but you can just write a lambda / custom function

    \(a,b,c,d) -> [a,b,c,d]

You should ask yourself the question why you have such a tuple in the first place. Big-ish homogeneous tuples seem fishy; probably you should instead built a list right where it comes from instead.

leftaroundabout
  • 117,950
  • 5
  • 174
  • 319
5

Bonus answer: if you were using lens, you could do it with the each traversal. each can handle tuples of various sizes because it relies on an Each class that has instances for them.

GHCi> import Control.Lens
GHCi> toListOf each (Left "Error1", Right 1, Left "Error2", Right 2)
[Left "Error1",Right 1,Left "Error2",Right 2]

Yet another possibility would be relying on Foldable instances for homogeneous tuples provided by the tuples-homogenous-h98 package.

GHCi> import Data.Foldable
GHCi> import Data.Tuple.Homogenous
GHCi> toList (Tuple4 (Left "Error1", Right 1, Left "Error2", Right 2))
[Left "Error1",Right 1,Left "Error2",Right 2]

This digression aside, I subscribe to leftaroundabout's answer.

duplode
  • 33,731
  • 7
  • 79
  • 150
  • what if i got something like this (Left "Error1", Right 1, Left "Error2", Right "NameString") – Samuel D'costa Jun 20 '18 at 07:23
  • @SamuelD'costa Then you don't have an homogeneous tuple, and so you can't put all its elements in a list (as they have different types) unless you change them into something else. – duplode Jun 20 '18 at 12:09
3

You can convert a tuple with exactly four values in it to a list with exactly four values in it like:

f :: (a, a, a, a) -> [a]
f (a1, a2, a3, a4) = [a1, a2, a3, a4]

You can then proceed to use lefts :: [Either a b] -> [a] from Data.Either.

But as the answer to the opposite question, How do I convert a list to a tuple in Haskell?, suggests, in a general way, you can't. Generally when you have a specific number of elements (a tuple), you should want to know what to do with them specifically.

sshine
  • 15,635
  • 1
  • 41
  • 66