Testing a partial function in Scala - scala

I have no idea how to write a unit test for testing partial functions. For instance, consider an exercise from Chiusano et al's book;
where lazyUnit, as is defined in the same book, has the interface below
def lazyUnit[A] (a: => A): Par[A]
in which Par[A] is meant to be something that encapsulates a parallel computation whose result is of type A. Because Par[A] is not defined and lazyUnit is not defined neither, I find it not easy to design a unit test for testing the asyncF function. I thought about using something dynamic like isInstanceOf to check the function signatures, but I suppose that would not do more than just compiling the code.
Any idea?

Related

Reader monad in Scala: return, local, and sequence

I'm using the Reader monad in Scala as provided by the scalaz library. I'm familiar with this monad as defined in Haskell. The problem is that I cannot find the functions equivalent to return, local, and sequence (among others).
Currently I use constructs that I do not like since I'm repeating myself or making my code a bit obscure.
Regarding return, I'm currently using:
Reader{_ => someValue}
I'd rather just use a construct like unit(someValue), but I could not find anything on the internet. There are tutorials like this one that use the approach above, and which I consider not optimal.
Regarding local I also have to do something similar: instead of typing something like: local f myReader I have to unfold its definition:
Reader{env => myReader.run(f(env))
Finally, sequence is a bit closer to what I would expect (being a Haskell refugee doing Scala):
readers: List[Reader[Env, T]]
readerTs: Reader[Env, List[T]] = readers.sequenceU
My problem with this implementation is that, being relatively new to Scala, the type of sequenceU
final class TraverseOps[F[_],A] private[syntax](val self: F[A])(implicit val F: Traverse[F]) extends Ops[F[A]] {
//...
def sequenceU(implicit G: Unapply[Applicative, A]): G.M[F[G.A]]
appears like rather obscure, and seems like black magic. Ideally I would like to use a sequence operations on Monads.
Is there a better translation of these constructs to Scala available on scalaz or similar library? I'm not married to any Functional library for Scala, so any solution using other libraries will do, although I'd rather have an answer using scalaz, since I already implemented my code using it.
To make the things simpler, I fill in some types. Changing them to defs with generic types should still work.
Also I extracted the ReaderInt type, to avoid confusion with type lambdas.
return / pure / point
Scala does not have automatic typeclass resolution, so you need to provide them implicitly. For Kleisli (being a monad transformer for reader),
Kleisli[Id, ?, ?] is enough
implicit val KA = scalaz.Kleisli.kleisliIdApplicative[Int]
type ReaderInt[A] = Kleisli[Id.Id, Int, A]
val alwaysHello = KA.point("hello")
or with imported syntax:
import scalaz.syntax.applicative._
val alwaysHello = "hello".point[ReaderInt]
So as a general rule, you
1) import the applicative intance, which usually located in scalaz.std.something.somethingInstance
2) import scalaz.syntax.something._
3) then you can write x.point[F], where F is your applicative.
local
Not sure, that it answers your question, but Kleisli has a local method.
val f: String ⇒ Int = _.length
val alwaysEleven = alwaysHello local f
sequencing
The same way, you are free to choose to use syntax for or to specify type classes explicitly.
import scalaz.std.list.listInstance
val initial: List[ReaderInt[String]] = ???
val sequenced: ReaderInt[List[String]] = Traverse[List].sequence[ReaderInt, String](initial)
import scalaz.syntax.traverse._
val z = x.sequence[ReaderInt, String]
I prefer not to use sequenceU, which uses Unapply typelcass to infer the G type, because sometimes scala has troubles of figuring out the right one.
And I personally do not find it messy to put in some types myself.
It may worth to look into cats, though it does not have much yet.

What exactly makes Option a monad in Scala?

I know what the monads are and how to use them. What I don't understand is what makes, let's say, Option a monad?
In Haskell a monad Maybe is a monad because it's instantiated from Monad class (which has at least 2 necessary functions return and bind that makes class Monad, indeed, a monad).
But in Scala we've got this:
sealed abstract class Option[+A] extends Product with Serializable { ... }
trait Product extends Any with Equals { ... }
Nothing related to a monad.
If I create my own class in Scala, will it be a monad by default? Why not?
Monad is a concept, an abstract interface if you will, that simply defines a way of composing data.
Option supports composition via flatMap, and that's pretty much everything that is needed to wear the "monad badge".
From a theoretical point of view, it should also:
support a unit operation (return, in Haskell terms) to create a monad out of a bare value, which in case of Option is the Some constructor
respect the monadic laws
but this is not strictly enforced by Scala.
Monads in scala are a much looser concept that in Haskell, and the approach is more practical.
The only thing monads are relevant for, from a language perspective, is the ability of being used in a for-comprehension.
flatMap is a basic requirement, and you can optionally provide map, withFilter and foreach.
However, there's no such thing as strict conformance to a Monad typeclass, like in Haskell.
Here's an example: let's define our own monad.
class MyMonad[A](value: A) {
def map[B](f: A => B) = new MyMonad(f(value))
def flatMap[B](f: A => MyMonad[B]) = f(value)
override def toString = value.toString
}
As you see, we're only implementing map and flatMap (well, and toString as a commodity).
Congratulations, we have a monad! Let's try it out:
scala> for {
a <- new MyMonad(2)
b <- new MyMonad(3)
} yield a + b
// res1: MyMonad[Int] = 5
Nice! We are not doing any filtering, so we don't need to implement withFilter. Also since we're yielding a value, we don't need foreach either. Basically you implement whatever you wish to support, without strict requirements. If you try to filter in a for-comprehension and you haven't implemented withFilter, you'll simply get a compile-time error.
Anything that (partially) implements, through duck-typing, the FilterMonadic trait is considered to be a monad in Scala. This is different than how monads are represented in Haskell, or the Monad typeclass in scalaz. However, in order to benefit of the for comprehension syntactic sugar in Scala, an object has to expose some of the methods defined in the FilterMonadic trait.
Also, in Scala, the equivalent of the Haskell return function is the yield keyword used for producing values out of a for comprehension. The desugaring of yield is a call to the map method of the "monad".
The way I'd put it is that there's an emerging distinction between monads as a design pattern vs. a first-class abstraction. Haskell has the latter, in the form of the Monad type class. But if you have a type that has (or can implement) the monadic operations and obeys the laws, that's a monad as well.
These days you can see monads as a design pattern in Java 8's libraries. The Optional and Stream types in Java 8 come with a static of method that corresponds to Haskell return, and a flatMap method. There is however no Monad type.
Somewhere in between you also have the "duck-typed" approach, as Ionuț G. Stan's answer calls out. C# has this as well—LINQ syntax isn't tied to a specific type, but rather it can be used with any class that implements certain methods.
Scala, per se, does not provide the notion of a monad. You can express a monad as a typeclass but Scala also doesn't provide the notion of a typeclass. But Cats does. So you can create a Monad in Scala with the necessary boiler plate, e.g. traits and implicits cleverly used, or you can use cats which provides a monad trait out of the box. As a comparison, Haskel provides monads as part of the language. Regarding your specific question, an Option can be represented as a monad because it has a flatMap method and a unit method (wrapping a value in a Some or a Future, for example).

How to generalize Future.sequence in Scala

I'm trying to understand the Scala type system, and generalize the concept of Future.sequence which has type List[Future[T]] => Future[List[T]]. We can try to generalize this concept by defining a function of type A[B[C]] => B[A[C].
What is the best way to do this? I was thinking of something along the lines of the following (note that I'm using names that suggest this is a monoid, but it's not really a monoid even though it looks kind of similar):
trait Flippable[A[B[C]], B[_], C] {
def mappend(a1: B[A[C]], a2: B[C]): B[A[C]]
def mzero: B[A[C]]
}
The above snippet does not compile because the types not consistently constrained to work with the api of the mappend and mzero. How can I specify appropriate constraints to make this compilable so that I can correctly generally define a function like Future.sequence? Are there existing higher order constructs/concepts that can be used (similar to monoid) to avoid defining the flippable trait from scratch as I'm attempting to do above?

Understanding Gen.unit(x)

Working through Functional Programming in Scala, the book shows the Gen Monad definition. Gen, as I understand, is a ScalaCheck trait.
val genMonad = new Monad[Gen] {
def unit[A](a => A): Gen[A] = Gen.unit(a)
def flatMap[A, B](ma: Gen[A])(f: A => Gen[B]) =
ma.flatMap(f)
}
I believe that OptionMonad.unit is defined as Some(a), but I don't understand Gen.unit(a).
How is Gen.unit(a) defined?
A Gen[A] is just an object which can be repeatedly called to give instances of type A. These "generators" are used to drive the ScalaCheck automated testing framework, which lets programmers specify properties of objects of a given type, and then repeatedly generates instances of that type and checks those properties. Gen forms a monad, which is to say it supports the operations of "unit" and "bind", about which approximately a zillion tutorials can be found on the internet. Scala's idioms for monads are a bit inconsistent, as monad types have a standard method of bind, called flatMap, but none for unit. This is because Scala is object oriented, and unit doesn't take an object of it's monad, but instead returns one, so it doesn't make any sense to make unit a method of the underlying class. Instead, most Scala monads leave the unit method implicit, often as a single-element constructor of the monad type.
So with that background out of the way, what's unit of Gen[A]. Well it needs to be something which takes an object of type A as an argument, and then allows repeated generation of objects of type A. Since A could literally be anything, there's really only one thing we can come up with which fits this bill. unit(a) must be a boring generator which repeatedly returns a . Simple once you think it through.

Tools to auto generating implicit wrappers in Scala

I am finding myself writing alot of boilerplate scala to add implicit class wrappers around modules of functions. For example, if I have this function defined for Seqs
def takeWhileRight[T](p: T=>Boolean)(s: Seq[T]): Seq[T] = s.reverse.takeWhile(p).reverse
I need to write this (completely deterministic) implicit wrapper:
implicit class EnrichSeq[T](value: Seq[T]) {
def takeWhileRight(p: T=>Boolean): Seq[T] = SeqOps.takeWhileRight(p)(value)
}
This is one example of many. In every case the implicit wrapper ends up being mechanically derivable from the function it forwards to.
Is anyone aware of any tools or code generators that can automate the generation of such wrappers?
You're using Scala 2.10's "implicit classes" already? The whole point (the only point) of that new syntactic sugar is to free you from having to write the implicit conversion method.