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 ?

Janus Lynd
  • 209
  • 1
  • 8

1 Answers1

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.

Ingo
  • 36,037
  • 5
  • 53
  • 100