https://kotlinlang.org logo
#fp-in-kotlin
Title
# fp-in-kotlin
r

Randall Perry

09/22/2021, 6:02 PM
Copy code
fun <A> sequence(fs: FList<Rand<A>>): Rand<FList<A>> = { rng ->
    when (fs) {
        is FList.Nil -> unit(FList.empty<A>())(rng)
        is FList.Cons -> {
            val (a, nrng) = fs.head(rng)
            val (xa, frng) = sequence(fs.tail)(nrng)
            FList.Cons(a, xa) to frng
        }
    }
}
This 1st answer was said to be not stack-safe, and the correct solution uses foldRight. But, I’m trying to understand the syntax. They have the ‘rng’ or the ‘nrng’ var enclosed in parantheses following the two return values:
Copy code
unit(FList.empty<A>())(rng)
Copy code
sequence(fs.tail)(nrng)
What does this mean? Is invoke being called via the parantheses? Or is the RNG type getting passed thru?
j

julian

10/03/2021, 12:53 AM
sequence
returns a lambda. So
sequence(...)(...)
calls
sequence
and executes the lambda returned by
sequence
. @Randall Perry
r

Randall Perry

10/10/2021, 4:35 PM
Ok thanks. Abstraction twice removed 😬
👍 1
j

julian

10/10/2021, 6:27 PM
It's natural in FP, because unlike OO, it's quite common for functions to produce other functions (i.e. lambdas). You get used to it after a while, and appreciate its power.
3 Views