Is there a built-in support for monad that deals with exception handling? Something similar to Scala\'s Try. I am asking because I don\'t like unchecked exceptions.
@Misha is onto something. Obviously you wouldn't do this exact thing in real code, but CompletableFuture provides Haskell-style monads like this:
return maps to CompletableFuture.completedFuture>= maps to thenComposeSo you could rewrite @Misha's example like this:
CompletableFuture.completedFuture(new Scanner(System.in)).thenCompose(scanner ->
CompletableFuture.completedFuture(scanner.nextInt()).thenCompose(divident ->
CompletableFuture.completedFuture(scanner.nextInt()).thenCompose(divisor ->
CompletableFuture.completedFuture(divident / divisor).thenCompose(val -> {
System.out.printf("%s/%s = %s%n", divident, divisor, val);
return null;
}))));
which maps to the Haskell-ish:
(return (newScanner SystemIn)) >>= \scanner ->
(return (nextInt scanner)) >>= \divident ->
(return (nextInt scanner)) >>= \divisor ->
(return (divident / divisor)) >>= \val -> do
SystemOutPrintf "%s/%s = %s%n" divident divisor val
return Null
or with do syntax
do
scanner <- return (newScanner SystemIn)
divident <- return (nextInt scanner)
divisor <- return (nextInt scanner)
val <- return (divident / divisor)
do
SystemOutPrintf "%s/%s = %s%n" divident divisor val
return Null
fmap and joinI got a little carried away. These are the standard fmap and join implemented in terms of CompletableFuture:
CompletableFuture fmap(Function f, CompletableFuture m) {
return m.thenCompose(x -> CompletableFuture.completedFuture(f.apply(x)));
}
CompletableFuture join(CompletableFuture> n) {
return n.thenCompose(x -> x);
}