-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add documentation for FlatMap and Bifunctor (#2459)
* Add documentation for FlatMap and Bifunctor * Fix page title
- Loading branch information
1 parent
04e8fcf
commit 8f1aafe
Showing
2 changed files
with
75 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
--- | ||
layout: docs | ||
title: "Bifunctor" | ||
section: "typeclasses" | ||
source: "core/src/main/scala/cats/Bifunctor.scala" | ||
scaladoc: "#cats.Bifunctor" | ||
--- | ||
# Bifunctor | ||
|
||
`Bifunctor` takes two type parameters instead of one, and is a functor in both | ||
of these parameters. It defines a function `bimap`, which allows for mapping over both | ||
arguments at the same time. Its signature is as follows: | ||
|
||
```scala | ||
def bimap[A, B, C, D](fab: F[A, B])(f: A => C, g: B => D): F[C, D] | ||
``` | ||
|
||
## Either as a Bifunctor | ||
|
||
Probably the most widely used Bifunctor instance is the Either data type. | ||
|
||
Say you have a value that is either an error or a `ZonedDateTime` instance. | ||
You also want to react to both possibilities - if there was a failure, you want to | ||
convert it to your own `DomainError`, and if the result was a success, you want to | ||
convert it to an UNIX timestamp. | ||
|
||
```tut:silent | ||
import cats._ | ||
import cats.implicits._ | ||
import java.time._ | ||
case class DomainError(message: String) | ||
def dateTimeFromUser: Either[Throwable, ZonedDateTime] = | ||
Right(ZonedDateTime.now()) // Example definition | ||
``` | ||
|
||
```tut:book | ||
dateTimeFromUser.bimap( | ||
error => DomainError(error.getMessage), | ||
dateTime => dateTime.toEpochSecond | ||
) | ||
``` | ||
|
||
`Bifunctor` also defines a convenience function called `leftMap`, which is defined as follows: | ||
|
||
```scala | ||
def leftMap[A, B, C](fab: F[A, B])(f: A => C): F[C, B] = bimap(fab)(f, identity) | ||
``` | ||
|
||
There is no `rightMap` however - use `map` instead. The reasoning behind this is that in Cats, the instances of | ||
`Bifunctor` are also mostly instances of `Functor`, as it is the case with `Either`. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters