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

com.github.tonivade.purefun.Applicable Maven / Gradle / Ivy

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

import static com.github.tonivade.purefun.Function2.first;
import static com.github.tonivade.purefun.Function2.second;

public interface Applicable extends Mappable {

  @Override
   Applicable map(Function1 mapper);

   Applicable ap(Kind> apply);
  
  default  Applicable> zip(Kind other) {
    return mapN(narrowK(this), narrowK(other), Tuple::of);
  }
  
  default  Applicable zipLeft(Kind other) {
    return mapN(narrowK(this), narrowK(other), first());
  }
  
  default  Applicable zipRight(Kind other) {
    return mapN(narrowK(this), narrowK(other), second());
  }
  
  default  Applicable zipWith(Kind other, Function2 mapper) {
    return mapN(narrowK(this), narrowK(other), mapper);
  }

  static  Applicable mapN(Applicable fa, Applicable fb, 
      Function2 mapper) {
    return fb.ap(fa.map(mapper.curried()));
  }

  static  Applicable mapN(
      Applicable fa, 
      Applicable fb, 
      Applicable fc, 
      Function3 mapper) {
    return fc.ap(mapN(fa, fb, (a, b) -> mapper.curried().apply(a).apply(b)));
  }

  static  Applicable mapN(
      Applicable fa, 
      Applicable fb, 
      Applicable fc, 
      Applicable fd, 
      Function4 mapper) {
    return fd.ap(mapN(fa, fb, fc, (a, b, c) -> mapper.curried().apply(a).apply(b).apply(c)));
  }

  static  Applicable mapN(
      Applicable fa, 
      Applicable fb, 
      Applicable fc, 
      Applicable fd, 
      Applicable fe, 
      Function5 mapper) {
    return fe.ap(mapN(fa, fb, fc, fd, (a, b, c, d) -> mapper.curried().apply(a).apply(b).apply(c).apply(d)));
  }
  
  @SuppressWarnings("unchecked")
  static  Applicable narrowK(Kind kind) {
    return (Applicable) kind;
  }
}