0
votes

I'm reading the book "Functional Programming in Scala" and I'm writing unit tests to check the implementation of the exercises.

One thing I'm not sure I understood is how to unit test exercises using function composition and passage of state, explained in the chapter 6 of the book.

For example one exercise (ex. 6.8 of the book) is related to the implementation of the function flatMap using passage of state, below the solution:

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

Now, I do understand the implementation of the solution, but I'm not able to figure out how to write a unit test for it. In detail, I understand how to pass Rand[A] as parameter for the function f, but I don't know how to build the function g, that should return a Rand[B].

Has anyone came up with a solution for it?

Thanks in advance.

1
is you question about testing the solution or using the solution? - pedrofurla
Hi @pedrofurla: testing the solution. - mtraina

1 Answers

0
votes

If you want to implement a function A => Rand[B] that takes an A and returns a Rand[B], you just need

  1. A way to create a Rand[B] (where this is defined as an alias for RNG => (B,RNG)). You can do it explicitly (by creating an RNG and defining the function) or you can use other functions that return a Rand[B] (such as unit, map, ...).
  2. A logic to produce a B from an A

    val g: RNG = // ...
    val ra: Rand[Int] = // ... you know how to build it, you say
    val rb: Rand[String] = flatMap(ra)(n => unit("hello")) // E.g., you ignore 'n'
    rb(g)._1 shouldEqual "hello"