mon/README.org
Paul Campbell 9a6c58c835 Rewrite README and convert to org-mode
* MaybeTest use static import Maybe.*
* Maybe.orElseThrow() now returns value when is a Just
2018-07-15 20:59:49 +01:00

23 KiB

Mon

Maven

    <dependency>
        <groupId>net.kemitix</groupId>
        <artifactId>mon</artifactId>
        <version>RELEASE</version>
    </dependency>

The latest version should be shown above with the nexus and maven-central badges or can be found on Maven Central.

Usage

TypeAlias

In Haskell it is possible to create an alias for a Type, and to then use that alias with the same behaviour as the original, except that the compiler doesn't treat the alias as the same Type and will generate compiler errors if you try and use them together. e.g.:

type PhoneNumber = String  
type Name = String  
type PhoneBook = [(Name,PhoneNumber)]

In Java we don't have the ability to have that true alias, so TypeAlias is more of a type-wrapper. It's as close as I could get to a Haskell type alias in Java.

The benefits of using TypeAlias are:

  • encapsulation of the wrapped type when passing references through code that doesn't need to access the actual value, but only to pass it on
  • type-safe parameters where you would otherwise be passing Strings, Integers, Lists, or other general classes
  • equality and hashcode
  • less verbose than implementing your own

TypeAlias Example:

class PhoneNumber extends TypeAlias<String> {
    private PhoneNumber(final String value) {
        super(value);
    }
    public static PhoneNumber of(final String phoneNumber) {
        return new PhoneNumber(phoneNumber);
    }
}

Roll your own:

class PhoneNumber {
    private final String value;
    private PhoneNumber(final String value) {
        this.value = value;
    }
    public static PhoneNumber of(final String phoneNumber) {
        return new PhoneNumber(phoneNumber);
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PhoneNumber that = (PhoneNumber) o;
        return Objects.equals(value, that.value);
    }
    @Override
    public int hashCode() {
        return Objects.hash(value);
    }
    public String getValue() {
        return value;
    }
}

Lombok:

Although, if you are using Lombok, that can be equally terse, both it and TypeAlias<String> coming in at 8 lines each, compared to 24 for rolling your own:

@Value
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
class PhoneNumber {
    private final String value;
    public static PhoneNumber of(final String phoneNumber) {
        return new PhoneNumber(phoneNumber);
    }
}

Maybe

Allows specifying that a value may or may not be present. Similar to Optional. Maybe provides additional methods that Optional doesn't: isNothing(), stream(), ifNothing() and match(). Maybe does not have a get() method.

Unlike Optional, when a map() results in a null, the Maybe will continue to be a Just. Optional would switch to being empty. vavi.io follows the same behaviour as Maybe.

import net.kemitix.mon.maybe.Maybe;

import java.util.function.Function;
import java.util.function.Predicate;

class MaybeExample {

    public static void main(String[] args) {
        Maybe.just(countArgs(args))
             .filter(isEven())
             .map(validMessage())
             .match(
                 just -> System.out.println(just),
                 () -> System.out.println("Not an valid value")
             );
    }

    private static Function<Integer, String> validMessage() {
        return v -> String.format("Value %d is even", v);
    }

    private static Predicate<Integer> isEven() {
        return v -> v % 2 == 0;
    }

    private static Integer countArgs(String[] args) {
        return args.length;
    }
}

In the above example, the number of command line arguments are counted, if there are an even number of them then a message is created and printed by the Consumer parameter in the match call. If there is an odd number of arguments, then the filter will return Maybe.nothing(), meaning that the nothing drops straight through the map and triggers the Runnable parameter in the match call.

Maybe is a Monad:
package net.kemitix.mon;

import net.kemitix.mon.maybe.Maybe;
import org.assertj.core.api.WithAssertions;
import org.junit.Test;

import java.util.function.Function;

public class MaybeMonadTest implements WithAssertions {

    private final int v = 1;
    private final Function<Integer, Maybe<Integer>> f = i -> m(i * 2);
    private final Function<Integer, Maybe<Integer>> g = i -> m(i + 6);

    private static Maybe<Integer> m(int value) {
        return Maybe.maybe(value);
    }

    @Test
    public void leftIdentity() {
        assertThat(
                m(v).flatMap(f)
        ).isEqualTo(
                f.apply(v)
        );
    }

    @Test
    public void rightIdentity() {
        assertThat(
                m(v).flatMap(x -> m(x))
        ).isEqualTo(
                m(v)
        );
    }

    @Test
    public void associativity() {
        assertThat(
                m(v).flatMap(f).flatMap(g)
        ).isEqualTo(
                m(v).flatMap(x -> f.apply(x).flatMap(g))
        );
    }

}
Static Constructors
static <T> Maybe<T> maybe(T value)

Create a Maybe for the value that may or may not be present.

Where the value is null, that is taken as not being present.

final Maybe<Integer> just = Maybe.maybe(1);
final Maybe<Integer> nothing = Maybe.maybe(null);
static <T> Maybe<T> just(T value)

Create a Maybe for the value that is present.

The value must not be null or a NullPointerException will be thrown. If you can't prove that the value won't be null you should use Maybe.maybe(value) instead.

final Maybe<Integer> just = Maybe.just(1);
static <T> Maybe<T> nothing()

Create a Maybe for a lack of a value.

final Maybe<Integer> nothing = Maybe.nothing();
Instance Methods
Maybe<T> filter(Predicate<T> predicate)

Filter a Maybe by the predicate, replacing with Nothing when it fails.

final Maybe<Integer> maybe = Maybe.maybe(getValue())
                                  .filter(v -> v % 2 == 0);
<R> Maybe<R> map(Function<T,R> f)

Applies the function to the value within the Maybe, returning the result within another Maybe.

final Maybe<Integer> maybe = Maybe.maybe(getValue())
                                  .map(v -> v * 100);
<R> Maybe<R> flatMap(Function<T,Maybe<R>> f)

Applies the function to the value within the Maybe, resulting in another Maybe, then flattens the resulting Maybe<Maybe<T>> into Maybe<T>.

Monad binder maps the Maybe into another Maybe using the binder method f

final Maybe<Integer> maybe = Maybe.maybe(getValue())
                                  .flatMap(v -> Maybe.maybe(getValueFor(v)));
void match(Consumer<T> just, Runnable nothing)

Matches the Maybe, either just or nothing, and performs either the Consumer, for Just, or Runnable for nothing.

Maybe.maybe(getValue())
     .match(
         just -> workWithValue(just),
           () -> nothingToWorkWith()
     );
T orElse(T otherValue)

A value to use when Maybe is Nothing.

final Integer value = Maybe.maybe(getValue())
                           .orElse(1);
T orElseGet(Supplier<T> otherValueSupplier)

Provide a value to use when Maybe is Nothing.

final Integer value = Maybe.maybe(getValue())
                           .orElseGet(() -> getDefaultValue());
void orElseThrow(Supplier<Exception> error)

Throw the exception if the Maybe is a Nothing.

final Integer value = Maybe.maybe(getValue())
                           .orElseThrow(() -> new RuntimeException("error"));
Maybe<T> peek(Consumer<T> consumer)

Provide the value within the Maybe, if it exists, to the Consumer, and returns this Maybe. Conceptually equivalent to the idea of ifPresent(...).

final Maybe<Integer> maybe = Maybe.maybe(getValue())
                                  .peek(v -> v.foo());
void ifNothing(Runnable runnable)

Run the runnable if the Maybe is a Nothing, otherwise do nothing.

Maybe.maybe(getValue())
     .ifNothing(() -> doSomething());
Stream<T> stream()

Converts the Maybe into either a single value stream or an empty stream.

final Stream<Integer> stream = Maybe.maybe(getValue())
                                    .stream();
boolean isJust()

Checks if the Maybe is a Just.

final boolean isJust = Maybe.maybe(getValue())
                            .isJust();
boolean isNothing()

Checks if the Maybe is Nothing.

final boolean isNothing = Maybe.maybe(getValue())
                               .isNothing();
Optional<T> toOptional()

Convert the Maybe to an Optional.

final Optional<Integer> optional = Maybe.maybe(getValue())
                                        .toOptional();

Result

Allows handling error conditions without the need to catch exceptions.

When a Result is returned from a method it will contain one of two values. Either the actual result, or an error in the form of an Exception. The exception is returned within the Result and is not thrown.

import net.kemitix.mon.result.Result;

import java.io.IOException;

class ResultExample implements Runnable {

    public static void main(final String[] args) {
        new ResultExample().run();
    }

    @Override
    public void run() {
        Result.of(() -> callRiskyMethod())
              .flatMap(state -> doSomething(state))
              .match(
                  success -> System.out.println(success),
                  error -> error.printStackTrace()
              );
    }

    private String callRiskyMethod() throws IOException {
        return "I'm fine";
    }

    private Result<String> doSomething(final String state) {
        return Result.of(() -> state + ", it's all good.");
    }

}

In the above example the string "I'm fine" is returned by callRiskyMethod() within a successful Result. The .flatMap() call, unwraps that Result and, as it is a success, passes the contents to doSomething(), which in turn returns a Result that the .flatMap() call returns. match() is called on the Result and, being a success, will call the success Consumer.

Had callRiskyMethod() thrown an exception it would have been caught by the Result.of() method which would have then been an error Result. An error Result would have ignored the flatMap and skipped to the match() when it would have called the error Consumer.

Result is a Monad
package net.kemitix.mon;

import net.kemitix.mon.result.Result;
import org.assertj.core.api.WithAssertions;
import org.junit.Test;

import java.util.function.Function;

public class ResultMonadTest implements WithAssertions {

    private final int v = 1;
    private final Function<Integer, Result<Integer>> f = i -> r(i * 2);
    private final Function<Integer, Result<Integer>> g = i -> r(i + 6);

    private static Result<Integer> r(int v) {
        return Result.ok(v);
    }

    @Test
    public void leftIdentity() {
        assertThat(
                r(v).flatMap(f)
        ).isEqualTo(
                f.apply(v)
        );
    }

    @Test
    public void rightIdentity() {
        assertThat(
                r(v).flatMap(x -> r(x))
        ).isEqualTo(
                r(v)
        );
    }

    @Test
    public void associativity() {
        assertThat(
                r(v).flatMap(f).flatMap(g)
        ).isEqualTo(
                r(v).flatMap(x -> f.apply(x).flatMap(g))
        );
    }

}
Static Constructors
static <T> Result<T> of(Callable<T> callable)

Create a Result for a output of the Callable.

If the Callable throws and Exception, then the Result will be an error and will contain that exception.

This will be the main starting point for most Results where the callable could throw an Exception.

final Result<Integer> okay = Result.of(() -> 1);
final Result<Integer> error = Result.of(() -> {throw new RuntimeException();});
static <T> Result<T> ok(T value)

Create a Result for a success.

Use this where you have a value that you want to place into the Result context.

final Result<Integer> okay = Result.ok(1);
static <T> Result<T> error(Throwable error)

Create a Result for an error.

final Result<Integer> error = Result.error(new RuntimeException());
Static Methods

These static methods provide integration with the Maybe class.

static <T> Maybe<T> toMaybe(Result<T> result)

Creates a Maybe from the Result, where the Result is a success, then the Maybe will contain the value. However, if the Result is an error then the Maybe will be nothing.

final Result<Integer> result = Result.of(() -> getValue());
final Maybe<Integer> maybe = Result.toMaybe(result);
static <T> Result<T> fromMaybe(Maybe<T> maybe, Supplier<Throwable> error)

Creates a Result from the Maybe, where the Result will be an error if the Maybe is nothing. Where the Maybe is nothing, then the Supplier<Throwable> will provide the error for the Result.

final Maybe<Integer> maybe = Maybe.maybe(getValue());
final Result<Integer> result = Result.fromMaybe(maybe, () -> new NoSuchFileException("filename"));
static <T> Result<Maybe<T>> invert(Maybe<Result<T>> maybeResult)

Swaps the Result within a Maybe, so that Result contains a Maybe.

final Maybe<Result<Integer>> maybe = Maybe.maybe(Result.of(() -> getValue()));
final Result<Maybe<Integer>> result = Result.invert(maybe);
static <T,R> Result<Maybe<R>> flatMapMaybe(Result<Maybe<T>> maybeResult, Function<Maybe<T>,Result<Maybe<R>>> f)

Applies the function to the contents of a Maybe within the Result.

final Result<Maybe<Integer>> result = Result.of(() -> Maybe.maybe(getValue()));
final Result<Maybe<Integer>> maybeResult = Result.flatMapMaybe(result, maybe -> Result.of(() -> maybe.map(v -> v * 2)));
Instance Methods
<R> Result<R> map(Function<T,R> f)

Applies the function to the value within the Functor, returning the result within a Functor.

final Result<String> result = Result.of(() -> getValue())
                                    .map(v -> String.valueOf(v));
<R> Result<R> flatMap(Function<T,Result<R>> f)

Returns a new Result consisting of the result of applying the function to the contents of the Result.

final Result<String> result = Result.of(() -> getValue())
                                    .flatMap(v -> Result.of(() -> String.valueOf(v)));
<R> Result<R> andThen(Function<T,Callable<R>> f)

Maps a Success Result to another Result using a Callable that is able to throw a checked exception.

final Result<String> result = Result.of(() -> getValue())
                                    .andThen(v -> () -> {throw new IOException();});
void match(Consumer<T> onSuccess, Consumer<Throwable> onError)

Matches the Result, either success or error, and supplies the appropriate Consumer with the value or error.

Result.of(() -> getValue())
      .match(
          success -> System.out.println(success),
          error -> System.err.println("error")
      );
Result<T> recover(Function<Throwable,Result<T>> f)

Provide a way to attempt to recover from an error state.

final Result<Integer> result = Result.of(() -> getValue())
                                     .recover(e -> Result.of(() -> getSafeValue(e)));
Result<T> peek(Consumer<T> consumer)

Provide the value within the Result, if it is a success, to the Consumer, and returns this Result.

final Result<Integer> result = Result.of(() -> getValue())
                                     .peek(v -> System.out.println(v));
Result<T> thenWith(Function<T,WithResultContinuation<T>> f)

Perform the continuation with the current Result value then return the current Result, assuming there was no error in the continuation.

 final Result<Integer> result = Result.of(() -> getValue())
                                      .thenWith(v -> () -> System.out.println(v))
                                      .thenWith(v -> () -> {throw new IOException();});
Result<Maybe<T>> maybe(Predicate<T> predicate)

Wraps the value within the Result in a Maybe, either a Just if the predicate is true, or Nothing.

final Result<Maybe<Integer>> result = Result.of(() -> getValue())
                                            .maybe(v -> v % 2 == 0);
T orElseThrow()

Extracts the successful value from the result, or throws the error Throwable.

final Integer result = Result.of(() -> getValue())
                             .orElseThrow();
void onError(Consumer<Throwable> errorConsumer)

A handler for error states.

Result.of(() -> getValue())
      .onError(e -> handleError(e));
boolean isOkay()

Checks if the Result is a success.

final boolean isOkay = Result.of(() -> getValue())
                             .isOkay();
boolean isError()

Checks if the Result is an error.

final boolean isError = Result.of(() -> getValue())
                              .isError();