Last active
August 29, 2015 14:07
-
-
Save ceedubs/d705dc450596ae75e45c to your computer and use it in GitHub Desktop.
Turning List[Int => Int] into Int => List[Int] with cosequence
This file contains hidden or 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
import scalaz.std.function._ | |
import scalaz.syntax.functor._ | |
import scalaz.Functor | |
/* https://gist.github.com/ceedubs/f8273ede78f86df7df7f shows we can do this with sequenceU. | |
* Stephen Compall (S11001001) pointed out that cosequence can do this without requiring a | |
* Traverse instance of the outer type by using the Distributive instance of the inner type. | |
* (It still requires a Functor instance of the outer type, but many types such as Task, Future, | |
* etc have Functor but not Traverse.) | |
*/ | |
// proving we don't need the Traverse instance for List | |
implicit val listFunctor: Functor[List] = scalaz.std.list.listInstance | |
val add1: Int => Int = _ + 1 | |
val times2: Int => Int = _ * 2 | |
val squared: Int => Int = n => n * n | |
// we have to help the compiler out with cosequence :( | |
val combined: Int => List[Int] = List(add1, times2, squared).cosequence[({type l[a]= Int => a})#l, Int] | |
combined(4) // List(5, 8, 16) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment