BowenFu / hspp

hspp: An experimental library to bring Haskell Style Programming to C++.
https://bowenfu.github.io/hspp
Apache License 2.0
157 stars 0 forks source link

Implement try #66

Open BowenFu opened 1 year ago

BowenFu commented 1 year ago

try :: Exception e => IO a -> IO (Either e a)

BowenFu commented 1 year ago

Implement throw, throwIO, and onException io what = io catch \e -> do <- what throwIO (e :: SomeException)

BowenFu commented 1 year ago

data Async a = Async (MVar (Either SomeException a)) -- async :: IO a -> IO (Async a) async action = do var <- newEmptyMVar forkIO (do r <- try action; putMVar var r) -- return (Async var) waitCatch :: Async a -> IO (Either SomeException a) -- waitCatch (Async var) = readMVar var wait :: Async a -> IO a -- wait a = do r <- waitCatch a case r of Left e -> throwIO e Right a -> return a

BowenFu commented 1 year ago

bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c bracket before after during = do a <- before c <- during a onException after a after a return c

finally :: IO a -> IO b -> IO a finally io after = do io onException after after

BowenFu commented 1 year ago

waitEither :: Async a -> Async b -> IO (Either a b) waitEither a b = do m <- newEmptyMVar forkIO $ do r <- try (fmap Left (wait a)); putMVar m r forkIO $ do r <- try (fmap Right (wait b)); putMVar m r wait (Async m)

BowenFu commented 1 year ago

waitAny :: [Async a] -> IO a waitAny as = do m <- newEmptyMVar let forkwait a = forkIO $ do r <- try (wait a); putMVar m r mapM_ forkwait as wait (Async m)

BowenFu commented 1 year ago

Either has been implemented now.