All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.tonivade.purefun.instances.StateInstances Maven / Gradle / Ivy

/*
 * Copyright (c) 2018-2019, Antonio Gabriel Muñoz Conejo 
 * Distributed under the terms of the MIT License
 */
package com.github.tonivade.purefun.instances;

import static com.github.tonivade.purefun.Unit.unit;

import com.github.tonivade.purefun.Function1;
import com.github.tonivade.purefun.Higher1;
import com.github.tonivade.purefun.Instance;
import com.github.tonivade.purefun.Tuple;
import com.github.tonivade.purefun.Unit;
import com.github.tonivade.purefun.data.ImmutableList;
import com.github.tonivade.purefun.monad.State;
import com.github.tonivade.purefun.typeclasses.Console;
import com.github.tonivade.purefun.typeclasses.Monad;

public interface StateInstances {

  static  Monad> monad() {
    return new StateMonad() { };
  }

  static Console>> console() {
    return new ConsoleState();
  }
}

@Instance
interface StateMonad extends Monad> {

  @Override
  default  State pure(T value) {
    return State.pure(value);
  }

  @Override
  default  State flatMap(Higher1, T> value,
      Function1, R>> map) {
    return State.narrowK(value).flatMap(map.andThen(State::narrowK));
  }
}

@Instance
final class ConsoleState implements Console>> {

  @Override
  public State, String> readln() {
    return State., String>state(list -> Tuple.of(list.tail(), list.head().get()));
  }

  @Override
  public State, Unit> println(String text) {
    return State., Unit>state(list -> Tuple.of(list.append(text), unit()));
  }
}