Scalaz has so many abstractions and higher kinds that model lot of
algebraic structures, monads, hight level types to generalize common structures
and offers lot of tools that work with those abstractions.
In this article I wanted to cover the very basics. Ones we see every day
in standard scala library. What the anomalies of basic types are in standard
scala library, what are the comment things between them that can be made
generic, how to use scalaz with standard classes defined in scala library.
Scala is an object oriented language with functional aspects. Some people
like the object oriented aspect, some are attracted by the functional part.
Add to that the fact that it’s sitting on top of JVM and of course it’s
influenced by Java a lot, we still have nulls, we still have exceptions,
IO and state mutation, etc. And since Scala isn’t purely functional it still
allows us to write imperative code, call a Java library that will throw an
exception, etc. I personally think that functional code is easier to read and
understand, unit test and maintain(not event talking about state and multiple
threads). So when it comes to writing purely functional code (or as close to it
as possible) Scala sure misses certain things and scalaz has a lot built to
help. I decided to write series or posts to explain scalaz. I’ll start with the
basics, most common abstractions then explain more real words cases.
I’ll put the links to all posts here so it’s easy to navigate.
In my previous article about Semigroup, Monoid, Equal, Order, Enum
and Show. I covered what those are, what method they have and what derived
and syntax sugar methods scalaz bring for them. Also I showed that there are
implicit implementations of those for scala standard classes that once are
brought into the scope you’ll have access to those. In this article I’m gonna
show those methods in action for integer, string and boolean.
Applicative is Apply that also has point or pure methods.
Scalaz defines Applicative[F[_]] trait with point abstract method.
defpoint[A](a:=>A):F[A]
point method lifts A to F[A].
Since Applicative is Apply it inherits all the methods that Apply
offers plus it needs to provide implementation for map and ap methods.
Note that Applicative implements map using point and ap methods:
Bind is an Apply that also has bind method.
Scalaz defines Bind[F[_]] trait with bind abstract method.
defbind[A, B](fa:F[A])(f:A=>F[B]):F[B]
Having F[A] and mapping A to F[A] it returns F[B].
Since Bind is Apply it inherits all the methods that Apply offers plus
it needs to provide implementation for map and ap methods.
Note that Bind implements ap using bind and map methods:
Note that in Applicative, map method is implemented using
ap method and in Bind, ap is implemented using bind method. With that,
two methods that are left to be implemented for a Monad are
point and bind.