Skip to content

Commit

Permalink
Add flap function to Apply (#2588)
Browse files Browse the repository at this point in the history
* Add flap function to Apply

Add the `flap` function to `Apply` to facilitate combining a function in an
`Apply` context with a value which is not.

This is similar to `ap`:

```
def ap[A, B](ff: F[A => B])(fa: F[A]): F[B]
```

with the minor change of the value not being in a context:

```
def flap[A, B](ff: F[A => B])(a: A): F[B]
                              ^^^^
```

* Move mapApply to Function1 sytax extension

* Fix style errors

* Fix scalafmt error

* Add Function1Syntax to AllSyntaxBinCompat3
  • Loading branch information
ssanj authored and kailuowang committed Nov 16, 2018
1 parent 7b456fe commit 32e2aa6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
2 changes: 1 addition & 1 deletion core/src/main/scala/cats/syntax/all.scala
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,4 @@ trait AllSyntaxBinCompat2
with ListSyntaxBinCompat0
with ValidatedSyntaxBincompat0

trait AllSyntaxBinCompat3 extends UnorderedFoldableSyntax
trait AllSyntaxBinCompat3 extends UnorderedFoldableSyntax with Function1Syntax
33 changes: 33 additions & 0 deletions core/src/main/scala/cats/syntax/function1.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package cats
package syntax

trait Function1Syntax {

implicit def catsSyntaxFunction1[F[_]: Functor, A, B](fab: F[Function1[A, B]]): Function1Ops[F, A, B] =
new Function1Ops[F, A, B](fab)

final class Function1Ops[F[_]: Functor, A, B](fab: F[Function1[A, B]]) {

/**
* Given a function in the Functor context and a plain value, supplies the
* value to the function.
*
* Example:
* {{{
* scala> import cats.implicits._
*
* scala> val someF: Option[Int => Long] = Some(_.toLong + 1L)
* scala> val noneF: Option[Int => Long] = None
* scala> val anInt: Int = 3
*
* scala> someF.mapApply(anInt)
* res0: Option[Long] = Some(4)
*
* scala> noneF.mapApply(anInt)
* res1: Option[Long] = None
*
* }}}
*/
def mapApply(a: A): F[B] = Functor[F].map(fab)(_(a))
}
}

0 comments on commit 32e2aa6

Please sign in to comment.