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 contains_, foldSmash and mkString_ to FoldableOps #2123

Merged
merged 9 commits into from
Mar 16, 2018
Merged
Changes from 4 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
50 changes: 50 additions & 0 deletions core/src/main/scala/cats/syntax/foldable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,54 @@ final class FoldableOps[F[_], A](val fa: F[A]) extends AnyVal {

def foldr[B](b: Eval[B])(f: (A, Eval[B]) => Eval[B])(implicit F: Foldable[F]): Eval[B] =
F.foldRight(fa, b)(f)

/**
* test if `F[A]` contains an `A`, named contains_ to avoid conflict with existing contains which uses universal equality
*
* Example:
* {{{
* scala> import cats.implicits._
*
* scala> val l: List[Int] = List(1, 2, 3, 4)
* scala> l.contains_(1)
* res0: Boolean = true
* scala> l.contains_(5)
* res1: Boolean = false
* }}}
*/
def contains_[A](v: A)(implicit ev: Eq[A], F: Foldable[F]): Boolean =
F.exists(fa)(ev.eqv(_, v))


/**
* Intercalate with a prefix and a suffix
*
* Example:
* {{{
* scala> import cats.implicits._
*
* scala> val l: List[Int] = List("1", "2", "3")
* scala> l.foldSmash("List(", ",", ")")
* res0: String = List(1,2,3)
* }}}
*/
def foldSmash[A](prefix: A, delim: A, suffix: A)(implicit A: Monoid[A], F: Foldable[F]): A =
A.combine(prefix, A.combine(F.intercalate(fa, delim), suffix))



/**
* Make a string using `Show`, named as `mkString_` to avoid conflict
*
* Example:
* {{{
* scala> import cats.implicits._
*
* scala> val l: List[Int] = List(1, 2, 3)
* scala> l.mkString_("List(", ",", ")")
* res0: String = List(1,2,3)
* }}}
*/
def mkString_[A: Monoid](prefix: String, delim: String, suffix: String)(implicit F: Functor[F], S: Show[A], ev1: Monoid[String], ev2: Foldable[F]): String =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we not take Functor on this? If we implemented directly from foldLeft we could. Shame to take an additional constraint just to make implementation easier.

foldSmash(F.map(fa)(S.show))(prefix, delim, suffix)
}