How to choose a monoid of multiplication instead of adding a monoid?

I want to combine two lists:

import scalaz.syntax.align._ import scalaz.std.list._ import scalaz.std.anyVal._ List(1, 2, 3).merge(List(4, 5, 6, 7)) // Evaluates to List(5, 7, 9, 7) 

It uses the standard monoid padding implicitly. What if I want to use multiplication monoid instead? What is this idiomatic way to do this in Scalas?

+5
source share
1 answer

You can use the Multiplication tag to indicate that you want to use the multiplication monoid:

 import scalaz.Tags.Multiplication val xs = List(1, 2, 3).map(Multiplication(_)) val ys = List(4, 5, 6, 7).map(Multiplication(_)) 

And then:

 scala> xs merge ys res0: List[ scalaz.@ @[Int,scalaz.Tags.Multiplication]] = List(4, 10, 18, 7) 

Multiplication.unwrap removes the tag.

You can also explicitly pass your instance:

 scala> List(1, 2, 3).merge(List(4, 5, 6, 7))(Monoid.instance(_ * _, 1)) res1: List[Int] = List(4, 10, 18, 7) 

Using tags is more idiomatic.

+7
source

Source: https://habr.com/ru/post/1205260/


All Articles