Try monad in Java 8

后端 未结 6 2064
甜味超标
甜味超标 2020-12-30 04:15

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.

6条回答
  •  庸人自扰
    2020-12-30 05:04

    @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 thenCompose

    So 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
    

    Implementations of fmap and join

    I 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);
    }
    

提交回复
热议问题