Biraj Dhakal
Biraj Dhakal

Reputation: 107

How does this Scala function work?

def flatMap[A,B](f: Rand[A])(g: A => Rand[B]): Rand[B] =rng => {
    val (a, r1) = f(rng)
    g(a)(r1) 
}

I am confused by g(a)(r1) because g is supposed to take only one argument, so why r1?

Upvotes: 0

Views: 55

Answers (1)

RvanHeest
RvanHeest

Reputation: 869

I don't exactly know the Rand[A] structure, so this is partially guessing. What you are returning in this function is a Rand[B] and when you implement the function you start of with defining an argument rng of an anonymous function. This tells me that Rand is probably some kind of function itself.

In the second line (val (a, r1) = f(rng)) you apply the value rng to the instance f: Rand[A]. In the resulting tuple, a has type A.

Note with this that f(rng) is equal to explicitly calling apply: f.apply(rng).

You can use the value a to get a Rand[B] by applying this value to the function g. So, val rb: Rand[B] = g(a) (or g.apply(a)).

Now, you don't want to return an instance of Rand[B] in this anonymous function! Instead you need to apply the previous result r1 to this instance rb. So, you get rb(r1) or rb.apply(r1). Substituting rb with g(a) or g.apply(a) gives you g(a)(r1) or g.apply(a).apply(r1).

To summarize, as you said, g is supposed to only take one argument, which results in an instance of Rand[B], but that is not the expected return type here. You need to apply the result of the previous computation to this new computation to get the expected result.

Upvotes: 1

Related Questions