Combinig either type variables

Viewed 54

I have a function in Haskell which return type is Either error b, and there is "function x = Right b1" and for the "function (x:xs) b = I want to get something like Right [list of b's]. I don't really know how to explain that, I am new to haskell. I have tried: function (x:xs) = function x <$> function xs and function (x:xs) b = function x b <*> function xs b, but I get type mismatch errors. The only thing I want is to get not [Right b1, Right b2, ...] but, Right [b1, b2, b3].

1 Answers

You were actually quite close, if your function is f :: a -> Either b c, you can implement this with:

function :: [a] -> Either b [c]
function [] = Right []
function (x:xs) = (:) <$> f x <*> function xs

But there is no need to implement this yourself. This is a special case of traverse :: (Applicative f, Traversable t) => (a -> f b) -> t a -> f (t b) which can do this on any Traversable data structure, so you can work with:

function :: [a] -> Either b [c]
function = traverse f

If one of the function calls returns a Left …, the first one of the items in the list will be returned.

Related