Monads with Java 8

前端 未结 9 1063
礼貌的吻别
礼貌的吻别 2020-12-07 07:29

In the interests of helping to understand what a monad is, can someone provide an example using java ? Are they possible ?

Lambda expressions are possible using java

9条回答
  •  天命终不由人
    2020-12-07 08:17

    Java 8 will have lambdas; monads are a whole different story. They are hard enough to explain in functional programming (as evidenced by the large number of tutorials on the subject in Haskell and Scala).

    Monads are a typical feature of statically typed functional languages. To describe them in OO-speak, you could imagine a Monad interface. Classes that implement Monad would then be called 'monadic', provided that in implementing Monad the implementation obeys what are known as the 'monad laws'. The language then provides some syntactic sugar that makes working with instances of the Monad class interesting.

    Now Iterable in Java has nothing to do with monads, but as a example of a type that the Java compiler treats specially (the foreach syntax that came with Java 5), consider this:

    Iterable things = getThings(..);
    for (Something s: things) {  /* do something with s */ }
    

    So while we could have used Iterable's Iterator methods (hasNext and company) in an old-style for loop, Java grants us this syntactic sugar as a special case.

    So just as classes that implement Iterable and Iterator must obey the Iterator laws (Example: hasNext must return false if there is no next element) to be useful in foreach syntax - there would exist several monadic classes that would be useful with a corresponding do notation (as it is called in Haskell) or Scala's for notation.

    So -

    1. What are good examples of monadic classes?
    2. What would syntactic sugar for dealing with them look like?

    In Java 8, I don't know - I am aware of the lambda notation but I am not aware of other special syntactic sugar, so I'll have to give you an example in another language.

    Monads often serve as container classes (Lists are an example). Java already has java.util.List which is obviously not monadic, but here is Scala's:

    val nums = List(1, 2, 3, 4)
    val strs = List("hello", "hola")
    val result = for { // Iterate both lists, return a resulting list that contains 
                       // pairs of (Int, String) s.t the string size is same as the num.
      n <- nums        
      s <- strs if n == s.length 
    } yield (n, s)
    // result will be List((4, "hola")) 
    // A list of exactly one element, the pair (4, "hola")
    

    Which is (roughly) syntactic sugar for:

    val nums = List(1, 2, 3, 4)
    val strs = List("hello", "hola")
    val results = 
    nums.flatMap( n =>                 
      strs.filter(s => s.size == n).   // same as the 'if'
           map(s => (n, s))            // Same as the 'yield'
    )
    // flatMap takes a lambda as an argument, as do filter and map
    // 
    

    This shows a feature of Scala where monads are exploited to provide list comprehensions.

    So a List in Scala is a monad, because it obeys Scala's monad laws, which stipulate that all monad implementations must have conforming flatMap, map and filter methods (if you are interested in the laws, the "Monads are Elephants" blog entry has the best description I've found so far). And, as you can see, lambdas (and HoF) are absolutely necessary but not sufficient to make this kind of thing useful in a practical way.

    There's a bunch of useful monads besides the container-ish ones as well. They have all kinds of applications. My favorite must be the Option monad in Scala (the Maybe monad in Haskell), which is a wrapper type which brings about null safety: the Scala API page for the Option monad has a very simple example usage: http://www.scala-lang.org/api/current/scala/Option.html In Haskell, monads are useful in representing IO, as a way of working around the fact that non-monadic Haskell code has indeterminate order of execution.

    Having lambdas is a first small step into the functional programming world; monads require both the monad convention and a large enough set of usable monadic types, as well as syntactic sugar to make working with them fun and useful.

    Since Scala is arguably the language closest to Java that also allows (monadic) Functional Programming, do look at this Monad tutorial for Scala if you are (still) interested: http://james-iry.blogspot.jp/2007/09/monads-are-elephants-part-1.html

    A cursory googling shows that there is at least one attempt to do this in Java: https://github.com/RichardWarburton/Monads-in-Java -

    Sadly, explaining monads in Java (even with lambdas) is as hard as explaining full-blown Object oriented programming in ANSI C (instead of C++ or Java).

提交回复
热议问题