Skip to content

Commit

Permalink
FJ Stream foldRight
Browse files Browse the repository at this point in the history
  • Loading branch information
johnmcclean committed Aug 8, 2017
1 parent 50b2bfa commit 9beb7a3
Showing 1 changed file with 10 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@
import cyclops.companion.CompletableFutures.CompletableFutureKind;
import cyclops.companion.Optionals;
import cyclops.companion.Optionals.OptionalKind;
import cyclops.control.Eval;
import cyclops.control.Maybe;
import cyclops.control.*;
import cyclops.control.Reader;
import cyclops.control.Xor;
import cyclops.conversion.functionaljava.FromJDK;
import cyclops.conversion.functionaljava.FromJooqLambda;
import cyclops.monads.*;
Expand Down Expand Up @@ -103,15 +101,16 @@ public static <T,R> Stream<R> tailRecXor(T initial, Function<? super T, ? exten
return next.filter(Xor::isPrimary).map(Xor::get);
}

public static <T,R> R foldRight(Stream<T> stream,R identity, BiFunction<? super T, ? super R, ? extends R> fn){
return foldRightRec(stream,Eval.now(identity),(a,b)-> b.map(b2->fn.apply(a,b2))).get();
}
private static <T,R> Eval<R> foldRightRec(Stream<T> stream,Eval<R> identity, BiFunction<? super T, ? super Eval<R>, ? extends Eval<R>> fn){
public static <T,R> R foldRight(Stream<T> stream,R identity, BiFunction<? super T, ? super R, ? extends R> p){
class Step{
public Trampoline<R> loop(Stream<T> s, Function<? super R, ? extends Trampoline<R>> fn){
if (s.isEmpty())
return fn.apply(identity);
return Trampoline.more(()->loop(s.tail()._1(), rem -> Trampoline.more(() -> fn.apply(p.apply(s.head(), rem) )) ));

if(stream.isEmpty())
return identity;
else
return identity.flatMap(i-> fn.apply(stream.head(), foldRightRec(stream.tail()._1(), identity, fn)));
}
}
return new Step().loop(stream,i->Trampoline.done(i)).result();
}
/**
* Perform a For Comprehension over a Stream, accepting 3 generating functions.
Expand Down

0 comments on commit 9beb7a3

Please sign in to comment.