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

com.github.tonivade.purefun.instances.StreamInstances 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 java.util.Objects.requireNonNull;

import com.github.tonivade.purefun.Function1;
import com.github.tonivade.purefun.Higher1;
import com.github.tonivade.purefun.Instance;
import com.github.tonivade.purefun.Kind;
import com.github.tonivade.purefun.monad.IO;
import com.github.tonivade.purefun.stream.Stream;
import com.github.tonivade.purefun.stream.Stream.StreamOf;
import com.github.tonivade.purefun.typeclasses.Applicative;
import com.github.tonivade.purefun.typeclasses.Functor;
import com.github.tonivade.purefun.typeclasses.Monad;

public interface StreamInstances {

  static StreamOf ofIO() {
    return Stream.of(IOInstances.monadDefer());
  }

  static  Functor> functor() {
    return new StreamFunctor() {};
  }

  static  Applicative> applicative(StreamOf streamOf) {
    requireNonNull(streamOf);
    return new StreamApplicative() {

      @Override
      public StreamOf streamOf() { return streamOf; }
    };
  }

  static  Monad> monad(StreamOf streamOf) {
    requireNonNull(streamOf);
    return new StreamMonad() {

      @Override
      public StreamOf streamOf() { return streamOf; }
    };
  }
}

@Instance
interface StreamFunctor extends Functor> {

  @Override
  default  Stream map(Higher1, T> value, Function1 mapper) {
    return Stream.narrowK(value).map(mapper);
  }
}

@Instance
interface StreamPure extends Applicative> {

  StreamOf streamOf();

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

@Instance
interface StreamApplicative extends StreamPure {

  @Override
  default  Stream ap(Higher1, T> value,
      Higher1, Function1> apply) {
    return Stream.narrowK(value).flatMap(t -> Stream.narrowK(apply).map(f -> f.apply(t)));
  }
}

@Instance
interface StreamMonad extends Monad>, StreamPure {

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




© 2015 - 2025 Weber Informatics LLC | Privacy Policy