Forum Stats

  • 3,827,140 Users
  • 2,260,744 Discussions


How easy is it to create your own monads?

user4612711 Member Posts: 1
edited Apr 11, 2014 9:05AM in Java 8 Questions

How easy is it to create your own monads?


  • From a practical perspective, there isn't much reason to create monads in Java. After all, even Java 8 is still an imperative, not a functional programming language, and as such monadic per se. Which is to say it provides all the things that e. g. Haskell needs monads for out-of-the-box, like IO, exception handling etc.

    From an academic perspective, if you perhaps want to understand Haskell monads by re-creating something similar in Java, your main concern will be the weakness of Java type inference. Picking the concept of Functor as an example, you might want to say something like this:

     public class Functor<X<?>> { public <A,B> X<B> map(Function<A,B> fn, X<A> source) { ... } } 

    But this is impossible in Java. We can't say "regardless of what X is, if you put an X<A> in map, you will get an X<B> back". There is no obvious way to abstract over the container, in order to write functors for lists, sets, maps, strings, functions etc.

    There are many blog postings about monads ("every programmer who gets monads blogs about it") and how to reconstruct them in Java. Good starting points that I can recommend are Bartosz Milewski's Programming Cafe and Haskell-style type classes in Java by Daniel Gronau, from which the above example is taken.

    Have fun,


This discussion has been closed.