I feel like a bit of a n00b because I find the Mon...
# arrow
k
I feel like a bit of a n00b because I find the Monoid docs not really helpful in understanding how to use Monoids in Arrow (I use them regularly in other FP programs). I have a
List<Map<String, String>>
and I want to fold it down to
Map<String, String>
. How could I do this using a Monoid in Arrow?
s
Hey @kierans777,
Iterable
has an extension
combineAll
that takes an
Monoid
argument, and if you look at the
Monoid.Companion
you will find all instances. On the
Monoid.Companion
we find
Monoid.map()
https://arrow-kt.io/docs/apidocs/arrow-core/arrow.typeclasses/-monoid/-companion/index.html
Which can be used together with
combineAll
which you can find on the
Extensions
page of Arrow Core. https://arrow-kt.io/docs/apidocs/arrow-core/arrow.core/index.html#functions https://arrow-kt.io/docs/apidocs/arrow-core/arrow.core/combine-all.html
We've put a lot of effort into the docs, but as in many projects, it's the very hardest part. Any help or contribution is always very much appreciated if you have some ideas for improving the docs on
Monoid
. I'm always happy to help if you have any questions in regards to contributing! So feel free to reach out here or in DM.
👍 1
k
Thanks for the reply @simon.vergauwen. Could you please give me an example of how to fold a
List<Map<String, String>>
to a`Map<String, String>` using a Monoid? I don't understand why
Monoid.map
requires an argument.
Copy code
val x = listOf(mapOf("one", "1"), mapOf("two", "2"), mapOf("three", "3"))
val y = ???

// I want y to look like
y = {
  "one": "1"
  "two": "2"
  "three": "3"
}
s
The reason for the argument to
map
is because you need to be able to combine values for duplicated keys.
Copy code
val x = listOf(mapOf("one" to "1"), mapOf("two" to "2"), mapOf("three" to "3"), mapOf("three" to "3"))
val y = x.combineAll(Semigroup.map(Semigroup.string())) // mapOf("one" to "1", "two" to "2", "three" to "33")
k
OK, in a statically typed language I can see why you need to do it like that.