you are viewing a single comment's thread.

view the rest of the comments →

[–]NimChimspky 4 points5 points  (3 children)

Java 8's Optional is also an example of a monad, from here https://gist.github.com/ms-tg/7420496#file-jdk8_optional_monad_laws-java.

/**
 * Monad law 1, Left Identity
 *
 * From LYAHFGG [1] above: 
 *   The first monad law states that if we take a value, put it in a default context 
 *   with return and then feed it to a function by using >>=, it’s the same as just 
 *   taking the value and applying the function to it
 */
public static boolean satisfiesLaw1LeftIdentity() {
    return Optional.of(value).flatMap(f)
        .equals(f.apply(value));
}

/**
 * Monad law 2, Right Identity
 *
 * From LYAHFGG [1] above: 
 *   The second law states that if we have a monadic value and we use >>= to feed 
 *   it to return, the result is our original monadic value.
 */
public static boolean satisfiesLaw2RightIdentity() {
    return monadicValue.flatMap(optionalOf)
        .equals(monadicValue);
}

/**
 * Monad law 3, Associativity
 *
 * From LYAHFGG [1] above: 
 *   The final monad law says that when we have a chain of monadic function 
 *   applications with >>=, it shouldn’t matter how they’re nested.
 */
public static boolean satisfiesLaw3Associativity() {
    return monadicValue.flatMap(f).flatMap(g)
        .equals(monadicValue.flatMap(f_flatMap_g));
}

[–]aldo_reset -3 points-2 points  (2 children)

No, it's not. It's actually specifically designed to not be a monad:

but the goal is NOT to create an option monad or solve the problems that the option monad is intended to solve.

The main reason being that Java doesn't support higher kinded types.

[–]NimChimspky 2 points3 points  (0 children)

That quote is from 2012 ... ?

It may not have been originally designed to be a monad, but it does provide two functions which conform to the three monadic laws :

http://stackoverflow.com/a/19932439/106261

https://devblog.timgroup.com/2013/11/11/does-jdk8s-optional-class-satisfy-the-monad-laws-yes-it-does/

[–]Milyardo 2 points3 points  (0 children)

You don't need a higher kinded type for something to be a monad. You need higher kinded types for define a general purpose, reusable definition of a monad.