Reputation: 34099
I have following function definition:
def addMonoid[A](items: List[A])(implicit monoid: Monoid[A]) =
items.foldLeft(monoid.empty)((a, b) => monoid.combine(a, b))
When I try to use it as follow:
add(List(Some(1), Some(2), Some(3)))
I've got:
Error:(35, 15) type mismatch;
found : Some[Int]
required: Int
add(List(Some(1), Some(2), Some(3)));}
^
What is wrong?
Upvotes: 1
Views: 92
Reputation: 25929
Also you can use Monoid directly in cats
import cats._
import cats.implicits._
Monoid[Option[Int]].combineAll(List(Some(1), Some(2), Some(3)))
Upvotes: 1
Reputation: 149598
Since a Monoid[Option]
is defined, and not a Monoid[Some]
, cats isn't finding an implicit in scope. If you use the some
syntax sugar cats provides which infers to Option[A]
, this will work:
def addMonoid[A: Monoid](items: List[A]) =
items.foldLeft(Monoid[A].empty)((a, b) => Monoid[A].combine(a, b))
addMonoid(List(1.some, 2.some, 3.some)).foreach(println)
Yields
6
Upvotes: 3