Skip to content

Commit

Permalink
Add fromOption to OptionT
Browse files Browse the repository at this point in the history
  • Loading branch information
frosforever committed Sep 12, 2015
1 parent c6816a1 commit 2e8a882
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
18 changes: 18 additions & 0 deletions core/src/main/scala/cats/data/OptionT.scala
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,24 @@ final case class OptionT[F[_], A](value: F[Option[A]]) {
object OptionT extends OptionTInstances {
def pure[F[_], A](a: A)(implicit F: Applicative[F]): OptionT[F, A] =
OptionT(F.pure(Some(a)))

/** Transforms an `Option` into an `OptionT`, lifted into the specified `Applicative`.
*
* Note: The return type is a FromOptionAux[F], which has an apply method on it, allowing
* you to call fromOption like this:
* {{{
* val t: Option[Int] = ...
* val x: OptionT[List, Int] = fromOption[List](t)
* }}}
*
* The reason for the indirection is to emulate currying type parameters.
*/
def fromOption[F[_]]: FromOptionAux[F] = new FromOptionAux

class FromOptionAux[F[_]] private[OptionT] {
def apply[A](value: Option[A])(implicit F: Applicative[F]): OptionT[F, A] =
OptionT(F.pure(value))
}
}

// TODO create prioritized hierarchy for Functor, Monad, etc
Expand Down
6 changes: 6 additions & 0 deletions tests/shared/src/test/scala/cats/tests/OptionTTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,12 @@ class OptionTTests extends CatsSuite {
}
})

test("fromOption")(check {
forAll { (o: Option[Int]) =>
List(o) == OptionT.fromOption[List](o).value
}
})

checkAll("OptionT[List, Int]", MonadTests[OptionT[List, ?]].monad[Int, Int, Int])
checkAll("MonadOptionT[List, ?]]", SerializableTests.serializable(Monad[OptionT[List, ?]]))
}

0 comments on commit 2e8a882

Please sign in to comment.