Created
June 15, 2013 01:11
-
-
Save puffnfresh/5786337 to your computer and use it in GitHub Desktop.
Something like what I want in an FFI to the JVM.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Java where | |
-- Small example of the type of interop I would like with Java | |
import Control.Monad.IO.Class | |
import Control.Monad.Trans.Maybe | |
import Control.Monad.Trans.Either | |
-- Pretend these actually came from Java | |
type Exception = String | |
type LinkedList = [] | |
-- Monadic Java interop | |
newtype Java a = Java { runJava :: MaybeT (EitherT Exception IO) a } | |
instance Monad Java where | |
j >>= f = Java (runJava j >>= runJava . f) | |
return = liftIO . return | |
instance MonadIO Java where | |
liftIO = Java . MaybeT . EitherT . fmap (Right . Just) | |
-- FFI function (pretend impl came from Java) | |
java_util_LinkedList_get :: Int -> IO (LinkedList a) -> Java a | |
java_util_LinkedList_get i = liftIO . fmap (!! i) | |
-- Haskell | |
plusTop :: IO (LinkedList Int) -> Java Int | |
plusTop l = do | |
a <- java_util_LinkedList_get 0 l | |
b <- java_util_LinkedList_get 1 l | |
return (a + b) | |
main :: IO () | |
main = do | |
-- Pretend the list came from Java | |
let javaList = return [1, 2, 3] | |
javaResult <- runEitherT . runMaybeT . runJava $ plusTop javaList | |
case javaResult of | |
Right (Just result) -> print result -- 3 | |
Right Nothing -> putStrLn "Got a null pointer" | |
Left exception -> putStrLn "Got exception:" >> print exception |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is a possible translation to Frege:
Here
try
andcatch
are just ordinary functions andMaybe a
onLinkedList.get
enables Frege automatically handle null elements.