Advertisement
Guest User

Untitled

a guest
Mar 4th, 2015
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. -- parseSQL :: String -> Either ParseError SQL
  2. -- evalSQL :: SQL -> IO (Either EvalError Table)
  3. -- prettyPrintTable :: Table -> IO ()
  4. -- ParseError, EvalError and Table are instances of Show
  5.  
  6. evalAndPrint :: String -> IO ()
  7. evalAndPrint x =
  8. case parseSQL x of
  9. (Left parseErr) ->
  10. print parseErr
  11. (Right sql) -> do
  12. result <- evalSQL sql
  13. case result of
  14. (Left err) ->
  15. print err
  16. (Right table) -> do
  17. prettyPrintTable table
  18. putStrLn $ "(" ++ show (length table) ++ " lines)n"
  19.  
  20. parseSQL :: MonadError ParseError m => String -> m SQL
  21. evalSQL :: (MonadError EvalError m, MonadIO m) => SQL -> m Table
  22.  
  23. -- if we were really doing this the mtl way, we'd introduce a new
  24. -- type class for changing error types instead of specializing to
  25. -- ExceptT, but that's another answer
  26. evalAndThrow :: String -> ExceptT String IO ()
  27. evalAndThrow s = do
  28. sql <- withExceptT show (parseSQL s)
  29. table <- withExceptT show (evalSQL sql)
  30. liftIO $ prettyPrintTable table
  31. liftIO . putStrLn $ "(" ++ show (length table) ++ " lines)n"
  32.  
  33. evalAndPrint s = do
  34. v <- runExceptT (evalAndThrow s)
  35. case v of
  36. Left err -> putStrLn err
  37. Right _ -> return ()
  38.  
  39. -- this is a generally useful combinator
  40. liftEither :: MonadError e m => Either e a -> m a
  41. liftEither = either throwError return
  42.  
  43. -- this is a combinator specific to your question
  44. liftIOEither :: (MonadError e m, MonadIO m) => IO (Either e a) -> m a
  45. liftIOEither = join . liftIO . liftM liftEither
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement