1

I'm trying to extract "a" and the error "b" from an expression of the type IO (Either a b).

I have this function, which returns a parsed file based on the file path

readFile' :: FilePath -> IO (Either a b)

And that's the way I'm trying to extract the values of a and b:

rFile :: FilePath -> String
rFile f = do
            l <- readFile' f
            case l of 
               Right n -> show n
               Left m  -> show m

This is the error message:

Couldn't match type `IO' with `[]'
  Expected type: [Either a b]
    Actual type: IO (Either a b)
* In a stmt of a 'do' block: l <- readFile' f
eak223223
  • 11
  • 1

1 Answers1

5

rFile can't return a String value, only an IO String value. (Or more precisely, the result of the do construct must be an IO String value, not a String.)

rFile :: FilePath -> IO String
rFile f = do
            l <- readFile' f
            return $ case l of 
               Right n -> show n
               Left m  -> show m

You can use fmap and either to get rid of both the explicit case analysis and the do syntax.

rFile f = fmap (either show show) (readFile' f)

(The obvious follow-up question, how do I get a String from an IO String, is one I'm not going to rehash here. For all practical intents and purposes, you don't.)

chepner
  • 497,756
  • 71
  • 530
  • 681