我正在做这个Scala 中的函数式编程练习:
// But what if our list has an element type that doesn't have a Monoid instance?
// Well, we can always map over the list to turn it into a type that does.
据我了解这个练习,这意味着,如果我们有一个类型为 Monoid B
,但我们的输入 List 是类型A
,那么我们需要将其转换List[A]
为List[B]
,然后调用foldLeft
。
def foldMap[A, B](as: List[A], m: Monoid[B])(f: A => B): B = {
val bs = as.map(f)
bs.foldLeft(m.zero)((s, i) => m.op(s, i))
}
这种理解和代码看起来对吗?