2

I'm trying to consume an infinite list which may contain elements of type:

IO (Either Throwable a)

  • I'm only interested in consuming elements of type Right.
  • List is sorted. Right elements are always first and then Left elements

The problem is that the implementation I'm using is wrong because the function sequence evaluates the infinite list, so function never ends.

takeWhileRight :: [IO (Either Throwable a)] -> IO [(Either Throwable a)]
takeWhileRight list = do
  unwrappedList <- sequence $ list -- BANG!!
  return $ takeWhile isRight $ unwrappedList

isRight :: (Either Throwable a) -> Bool
isRight x = case x of
  Right x -> true
  Left  x -> false

Any ideas about how to consume that list properly ?

1 Answer 1

2

Yes, this doesn't work with sequence

You need to do something like

takeWhileRight (x:xs) = do
  y <- x
  case y of
      Right -> (y:) <$> takeWhileRight xs
      Left  -> pure []
takeWhileRight [] = pure  []

(Untested.)

Note that the first IO action that gives a Left will still have to be run. This is unavoidable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.