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

Request to Add CoflatMap Instance for Vector #818

Merged
merged 5 commits into from
Jan 19, 2016
Merged
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
17 changes: 15 additions & 2 deletions core/src/main/scala/cats/std/vector.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@ package std
import cats.data.Streaming
import cats.syntax.show._

import scala.annotation.tailrec
import scala.collection.+:
import scala.collection.immutable.VectorBuilder

trait VectorInstances {
implicit val vectorInstance: Traverse[Vector] with MonadCombine[Vector] =
new Traverse[Vector] with MonadCombine[Vector] {
implicit val vectorInstance: Traverse[Vector] with MonadCombine[Vector] with CoflatMap[Vector] =
new Traverse[Vector] with MonadCombine[Vector] with CoflatMap[Vector] {

def empty[A]: Vector[A] = Vector.empty[A]

Expand All @@ -23,6 +27,15 @@ trait VectorInstances {
override def map2[A, B, Z](fa: Vector[A], fb: Vector[B])(f: (A, B) => Z): Vector[Z] =
fa.flatMap(a => fb.map(b => f(a, b)))

def coflatMap[A, B](fa: Vector[A])(f: Vector[A] => B): Vector[B] = {
@tailrec def loop(builder: VectorBuilder[B], as: Vector[A]): Vector[B] =
as match {
case _ +: rest => loop(builder += f(as), rest)
case _ => builder.result()
}
loop(new VectorBuilder[B], fa)
}

def foldLeft[A, B](fa: Vector[A], b: B)(f: (B, A) => B): B =
fa.foldLeft(b)(f)

Expand Down
6 changes: 5 additions & 1 deletion tests/src/test/scala/cats/tests/VectorTests.scala
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package cats
package tests

import cats.laws.discipline.{MonadCombineTests, SerializableTests, TraverseTests, MonoidalTests}
import cats.laws.discipline.{MonadCombineTests, CoflatMapTests, SerializableTests, TraverseTests, MonoidalTests}
import cats.laws.discipline.eq.tuple3Eq

class VectorTests extends CatsSuite {

checkAll("Vector[Int]", MonoidalTests[Vector].monoidal[Int, Int, Int])
checkAll("Monoidal[Vector]", SerializableTests.serializable(Monoidal[Vector]))

checkAll("Vector[Int]", CoflatMapTests[Vector].coflatMap[Int, Int, Int])
checkAll("CoflatMap[Vector]", SerializableTests.serializable(CoflatMap[Vector]))

checkAll("Vector[Int]", MonadCombineTests[Vector].monadCombine[Int, Int, Int])
checkAll("MonadCombine[Vector]", SerializableTests.serializable(MonadCombine[Vector]))

Expand Down