Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add flatTransform to OptionT (Issue #2309) #2313

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .jvmopts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
-Dfile.encoding=UTF8
-Xms1G
-Xmx6G
-XX:MaxPermSize=512M
-XX:MaxMetaspaceSize=512M
-XX:ReservedCodeCacheSize=250M
-XX:+TieredCompilation
-XX:-UseGCOverheadLimit
Expand Down
23 changes: 16 additions & 7 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,14 +112,23 @@ Cats cross-compiles to both JVM and Javascript(JS). If you are not used to
working with cross-compiling builds, the first things that you will notice is that
builds:

* Will take longer: To build JVM only, just use the `catsJVM`, or `catsJS` for

JS only. And if you want the default project to be `catsJVM`, just copy the
* Will take longer: To build JVM only, just use the `catsJVM`, or `catsJS`
for JS only. And if you want the default project to be `catsJVM`, just copy the
file `scripts/sbtrc-JVM` to `.sbtrc` in the root directory.

* May run out of memory: We suggest you use
[Paul Philips's sbt script](https://github.com/paulp/sbt-extras) that will use the settings from Cats.

### Editor Setup Tips

**IntelliJ**

- Be warned, IntelliJ is currently not 100% accurate at reporting compilation errors, there *will* be cases that it reports errors incorrectly. If you simply don't want to see the errors, a quick an easy work around is to disable *Type-Aware Highlighting* by clicking the `[T]` icon in the bottom toolbar.

- There is an open [issue](https://github.com/typelevel/cats/issues/2152) with the IntelliJ scala plugin, which prevents it from configuring similacrum correctly when importing the cats project. The work around for this issue is to set `val CompileTime = Provided` in `build.sbt`. Note: Be careful not to commit this change.

- IntelliJ does have [support](https://blog.jetbrains.com/scala/2015/07/31/inline-refactoring-for-type-aliases-and-kind-projector-support/) for kind-projector. However, it is not always seamless. If you are unable to get IntelliJ to recognise the special symbols that kind-project provides, such as `?` `Lambda[X => G[F[A]]]` or `λ[X => G[F[A]]]` try upgrading to the early access preview (EAP) version of the scala plugin. This can be done under `Settings > Languages & Frameworks > Scala > Updates`

### Write code

[See guidelines](/cats/guidelines.html).
Expand Down Expand Up @@ -185,13 +194,13 @@ run `sbt docs/makeMicrosite`

### Previewing the site

1. Install jekyll locally, depending on your platform, you might do this with:
1. Install jekyll locally. Depending on your platform, you might do this with:

yum install jekyll
`yum install jekyll`

apt-get install ruby-full; gem install jekyll
`apt-get install ruby-full; gem install jekyll`

gem install jekyll
`gem install jekyll`

2. In a shell, navigate to the generated site directory in `docs/target/site`

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ By sharing the same set of type classes, instances and data types provided by Ca
* [monadic-html](https://github.com/OlivierBlanvillain/monadic-html): Tiny DOM binding library for Scala.js
* [Monix](https://github.com/monix/monix): high-performance library for composing asynchronous and event-based programs
* [pureconfig](https://github.com/pureconfig/pureconfig): A boilerplate-free library for loading configuration files
* [rainier](https://github.com/stripe/rainier): Bayesian inference in Scala
* [scanamo](https://github.com/guardian/scanamo): simpler DynamoDB access for Scala
* [seals](https://github.com/durban/seals): tools for schema evolution and language-integrated schemata
* [tsec](https://github.com/jmcardon/tsec/): Typesafe, functional, general purpose cryptography and security library.
Expand Down
46 changes: 42 additions & 4 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ lazy val docSettings = Seq(
micrositeHomepage := "http://typelevel.org/cats/",
micrositeBaseUrl := "cats",
micrositeDocumentationUrl := "/cats/api/cats/index.html",
micrositeDocumentationLabelDescription := "API Documentation",
micrositeGithubOwner := "typelevel",
micrositeExtraMdFiles := Map(
file("CONTRIBUTING.md") -> ExtraMdFileConfig(
Expand Down Expand Up @@ -204,11 +205,48 @@ lazy val docSettings = Seq(
includeFilter in Jekyll := (includeFilter in makeSite).value
)

lazy val binaryCompatibleVersions = Set("1.0.0", "1.1.0")
def mimaSettings(moduleName: String) = {
import sbtrelease.Version

def semverBinCompatVersions(major: Int, minor: Int, patch: Int): Set[(Int, Int, Int)] = {
val majorVersions: List[Int] = List(major)
val minorVersions : List[Int] =
if (major >= 1) Range(0, minor).inclusive.toList
else List(minor)
def patchVersions(currentMinVersion: Int): List[Int] =
if (minor == 0 && patch == 0) List.empty[Int]
else if (currentMinVersion != minor) List(0)
else Range(0, patch - 1).inclusive.toList

val versions = for {
maj <- majorVersions
min <- minorVersions
pat <- patchVersions(min)
} yield (maj, min, pat)
versions.toSet
}

def mimaSettings(moduleName: String) = Seq(
mimaPreviousArtifacts := binaryCompatibleVersions.map(v => "org.typelevel" %% moduleName % v)
)
def mimaVersions(version: String): Set[String] = {
Version(version) match {
case Some(Version(major, Seq(minor, patch), _)) =>
semverBinCompatVersions(major.toInt, minor.toInt, patch.toInt)
.map{case (maj, min, pat) => s"${maj}.${min}.${pat}"}
case _ =>
Set.empty[String]
}
}
// Safety Net For Exclusions
lazy val excludedVersions: Set[String] = Set()

// Safety Net for Inclusions
lazy val extraVersions: Set[String] = Set()

Seq(
mimaPreviousArtifacts := (mimaVersions(version.value) ++ extraVersions)
.filterNot(excludedVersions.contains(_))
.map(v => "org.typelevel" %% moduleName % v)
)
}

lazy val docs = project
.enablePlugins(MicrositesPlugin)
Expand Down
7 changes: 6 additions & 1 deletion core/src/main/scala/cats/ApplicativeError.scala
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,12 @@ trait ApplicativeError[F[_], E] extends Applicative[F] {
* }}}
*/
def fromEither[A](x: E Either A): F[A] =
x.fold(raiseError, pure)
x match {
case Right(a) => pure(a)
case Left(e) => raiseError(e)
}


}

object ApplicativeError {
Expand Down
19 changes: 17 additions & 2 deletions core/src/main/scala/cats/Bitraverse.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,26 @@ import simulacrum.typeclass
*/
@typeclass trait Bitraverse[F[_, _]] extends Bifoldable[F] with Bifunctor[F] { self =>

/** Traverse each side of the structure with the given functions */
/**
* Traverse each side of the structure with the given functions.
*
* Example:
* {{{
* scala> import cats.implicits._
*
* scala> def parseInt(s: String): Option[Int] = Either.catchOnly[NumberFormatException](s.toInt).toOption
*
* scala> ("1", "2").bitraverse(parseInt, parseInt)
* res0: Option[(Int, Int)] = Some((1,2))
*
* scala> ("1", "two").bitraverse(parseInt, parseInt)
* res1: Option[(Int, Int)] = None
* }}}
*/
def bitraverse[G[_]: Applicative, A, B, C, D](fab: F[A, B])(f: A => G[C], g: B => G[D]): G[F[C, D]]

/**
* Sequence each side of the structure with the given functions.
* Invert the structure from F[G[A], G[B]] to G[F[A, B]].
*
* Example:
* {{{
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/scala/cats/Foldable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ import Foldable.sentinel

def collectFirst[A, B](fa: F[A])(pf: PartialFunction[A, B]): Option[B] =
foldRight(fa, Eval.now(Option.empty[B])) { (a, lb) =>
// trick from TravsersableOnce
// trick from TraversableOnce, used to avoid calling both isDefined and apply (or calling lift)
val x = pf.applyOrElse(a, sentinel)
if (x.asInstanceOf[AnyRef] ne sentinel) Eval.now(Some(x.asInstanceOf[B]))
else lb
Expand Down
127 changes: 124 additions & 3 deletions core/src/main/scala/cats/data/AndThen.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package cats.data
package cats
package data

import java.io.Serializable
import cats.arrow.{ArrowChoice, CommutativeArrow}


/**
* A function type of a single input that can do function composition
Expand All @@ -16,8 +19,48 @@ import java.io.Serializable
* // This should not trigger stack overflow ;-)
* f(0)
* }}}
*
* This can be used to build stack safe data structures that make
* use of lambdas. The perfect candidates for usage with `AndThen`
* are the data structures using a signature like this (where
* `F[_]` is a monadic type):
*
* {{{
* A => F[B]
* }}}
*
* As an example, if we described this data structure, the naive
* solution for that `map` is stack unsafe:
*
* {{{
* case class Resource[F[_], A, B](
* acquire: F[A],
* use: A => F[B],
* release: A => F[Unit]) {
*
* def flatMap[C](f: B => C)(implicit F: Functor[F]): Resource[F, A, C] = {
* Resource(
* ra.acquire,
* // Stack Unsafe!
* a => ra.use(a).map(f),
* ra.release)
* }
* }
* }}}
*
* To describe a `flatMap` operation for this data type, `AndThen`
* can save the day:
*
* {{{
* def flatMap[C](f: B => C)(implicit F: Functor[F]): Resource[F, A, C] = {
* Resource(
* ra.acquire,
* AndThen(ra.use).andThen(_.map(f)),
* ra.release)
* }
* }}}
*/
private[cats] sealed abstract class AndThen[-T, +R]
sealed abstract class AndThen[-T, +R]
extends (T => R) with Product with Serializable {

import AndThen._
Expand Down Expand Up @@ -97,7 +140,7 @@ private[cats] sealed abstract class AndThen[-T, +R]
"AndThen$" + System.identityHashCode(this)
}

private[cats] object AndThen {
object AndThen extends AndThenInstances0 {
/** Builds an [[AndThen]] reference by wrapping a plain function. */
def apply[A, B](f: A => B): AndThen[A, B] =
f match {
Expand All @@ -124,3 +167,81 @@ private[cats] object AndThen {
*/
private final val fusionMaxStackDepth = 127
}

private[data] abstract class AndThenInstances0 extends AndThenInstances1 {
/**
* [[cats.Monad]] instance for [[AndThen]].
*/
implicit def catsDataMonadForAndThen[T]: Monad[AndThen[T, ?]] =
new Monad[AndThen[T, ?]] {
// Piggybacking on the instance for Function1
private[this] val fn1 = instances.all.catsStdMonadForFunction1[T]

def pure[A](x: A): AndThen[T, A] =
AndThen(fn1.pure[A](x))

def flatMap[A, B](fa: AndThen[T, A])(f: A => AndThen[T, B]): AndThen[T, B] =
AndThen(fn1.flatMap(fa)(f))

override def map[A, B](fa: AndThen[T, A])(f: A => B): AndThen[T, B] =
AndThen(f).compose(fa)

def tailRecM[A, B](a: A)(f: A => AndThen[T, Either[A, B]]): AndThen[T, B] =
AndThen(fn1.tailRecM(a)(f))
}

/**
* [[cats.ContravariantMonoidal]] instance for [[AndThen]].
*/
implicit def catsDataContravariantMonoidalForAndThen[R : Monoid]: ContravariantMonoidal[AndThen[?, R]] =
new ContravariantMonoidal[AndThen[?, R]] {
// Piggybacking on the instance for Function1
private[this] val fn1 = instances.all.catsStdContravariantMonoidalForFunction1[R]

def unit: AndThen[Unit, R] =
AndThen(fn1.unit)

def contramap[A, B](fa: AndThen[A, R])(f: B => A): AndThen[B, R] =
fa.compose(f)

def product[A, B](fa: AndThen[A, R], fb: AndThen[B, R]): AndThen[(A, B), R] =
AndThen(fn1.product(fa, fb))
}

/**
* [[cats.arrow.ArrowChoice ArrowChoice]] and
* [[cats.arrow.CommutativeArrow CommutativeArrow]] instances
* for [[AndThen]].
*/
implicit val catsDataArrowForAndThen: ArrowChoice[AndThen] with CommutativeArrow[AndThen] =
new ArrowChoice[AndThen] with CommutativeArrow[AndThen] {
// Piggybacking on the instance for Function1
private[this] val fn1 = instances.all.catsStdInstancesForFunction1

def choose[A, B, C, D](f: AndThen[A, C])(g: AndThen[B, D]): AndThen[Either[A, B], Either[C, D]] =
AndThen(fn1.choose(f)(g))

def lift[A, B](f: A => B): AndThen[A, B] =
AndThen(f)

def first[A, B, C](fa: AndThen[A, B]): AndThen[(A, C), (B, C)] =
AndThen(fn1.first(fa))

override def split[A, B, C, D](f: AndThen[A, B], g: AndThen[C, D]): AndThen[(A, C), (B, D)] =
AndThen(fn1.split(f, g))

def compose[A, B, C](f: AndThen[B, C], g: AndThen[A, B]): AndThen[A, C] =
f.compose(g)
}
}

private[data] abstract class AndThenInstances1 {
/**
* [[cats.Contravariant]] instance for [[AndThen]].
*/
implicit def catsDataContravariantForAndThen[R]: Contravariant[AndThen[?, R]] =
new Contravariant[AndThen[?, R]] {
def contramap[T1, T0](fa: AndThen[T1, R])(f: T0 => T1): AndThen[T0, R] =
fa.compose(f)
}
}
Loading