Created
June 12, 2013 08:48
-
-
Save evantill/5763774 to your computer and use it in GitHub Desktop.
Traverse.sequence
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
package puzzle | |
import scalaz._ | |
import Scalaz._ | |
import scala.language.higherKinds | |
/** | |
* Created with IntelliJ IDEA. | |
* User: evantill | |
* Date: 11/06/13 | |
* Time: 15:09 | |
* To change this template use File | Settings | File Templates. | |
*/ | |
object RefactorPuzzle extends App{ | |
case class IntRdr[+A](read: Int => A) { | |
def map[B](f: A => B): IntRdr[B] = | |
IntRdr(f compose read) | |
def flatMap[B](f: A => IntRdr[B]): IntRdr[B] = | |
IntRdr(n => f(read(n)).read(n)) | |
} | |
object IntRdr { | |
implicit val intRdrInstance = new Monad[IntRdr] { | |
def point[A](a: => A): IntRdr[A] = IntRdr(a) | |
def bind[A, B](fa: IntRdr[A])(f: (A) => IntRdr[B]): IntRdr[B] = fa.flatMap(f) | |
} | |
def apply[A](a: A): IntRdr[A] = | |
IntRdr(_ => a) | |
} | |
// Return all the Some values, or None if not all are Some. | |
def runOptions[A](x: List[Option[A]]): Option[List[A]] = runSequence(x) | |
//x.foldRight[Option[List[A]]](Option(Nil))((a, b) => a.flatMap(aa => b.map(aa :: _))) | |
// Apply an Int to a list of int readers and return the list of return values. | |
def runIntRdrs[A](x: List[IntRdr[A]]): IntRdr[List[A]] = runSequence(x) | |
//x.foldRight[IntRdr[List[A]]](IntRdr(Nil))((a, b) => a.flatMap(aa => b.map(aa :: _))) | |
def runSequence[A,F[_]:Monad,L[_]:Traverse](x:L[F[A]] ): F[L[A]] = { | |
val F=implicitly[Monad[F]] | |
val L=implicitly[Traverse[L]] | |
L.sequence[F,A](x) | |
} | |
/* | |
def runMonads[A,F[_]:Monad](x:List[F[A]] ): F[List[A]] = { | |
val zero: F[List[A]] =implicitly[Monad[F]].pure[List[A]](Nil) | |
x.foldRight[F[List[A]]](zero)((a, b) => a.flatMap(aa => b.map(aa :: _))) | |
} | |
*/ | |
// Code Duplication | |
// ******* ************* ******* *********** | |
// def runOptions[A](x: List[Option[A]]): Option[List[A]] = | |
// def runIntRdrs[A](x: List[IntRdr[A]]): IntRdr[List[A]] = | |
// ************ *********** ************************************************* | |
// x.foldRight[Option[List[A]]](Option(Nil))((a, b) => a.flatMap(aa => b.map(aa :: _))) | |
// x.foldRight[IntRdr[List[A]]](IntRdr(Nil))((a, b) => a.flatMap(aa => b.map(aa :: _))) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment