Jakub Pi
04/23/2020, 3:39 PMfun <B> foldRightViaFoldLeft(identity: B, f: (A) -> (B) -> B): B =
this.reverse().foldLeft(identity) { x -> { y -> f(y)(x) } }
FP in Kotlin is still in Early Access so the solutions aren't yet available on their github page. But this is what I came up with (using an identity function and composition):
fun <A, B> foldRight2(xs: List<A>, z: B, f: (A, B) -> B): B = foldLeft(xs, {y : B -> y}) { g, a -> {x : B -> f(a, g(x))}}(z)
I've basically used foldLeft to build up a function that will evaluate in the same order as an equivalent foldRight and then executed it with the original identity value. Is this close to the accepted solution or are there downsides to this approach?stojan
04/23/2020, 3:44 PMJakub Pi
04/23/2020, 4:55 PMraulraja
04/23/2020, 6:25 PMJakub Pi
05/03/2020, 8:33 PMfun <A, B> foldLeftR(xs: List<A>, z: B, f: (B, A) -> B): B =
foldRight(xs, { b: B -> b }, { a, g -> { b -> g(f(b, a)) } })(z)
fun <A, B> foldRightL(xs: List<A>, z: B, f: (A, B) -> B): B =
foldLeft(xs, { b: B -> b }, { g, a -> { b -> g(f(a, b)) } })(z)
//expanded example
typealias Identity<B> = (B) -> B
fun <A, B> foldLeftRDemystified(
ls: List<A>,
acc: B,
combiner: (B, A) -> B
): B {
val identity: Identity<B> = { b: B -> b }
val combinerDelayer: (A, Identity<B>) -> Identity<B> =
{ a: A, delayedExec: Identity<B> ->
{ b: B ->
delayedExec(combiner(b, a))
}
}
val chain: Identity<B> = foldRight(ls, identity, combinerDelayer)
return chain(acc)
}