我在 Scala的以下练习中实现函数式编程的尝试如何?
// EXERCISE 5: Write a monoid instance for that String inserts spaces
// between words unless there already is one, and trims spaces off the ends of the
// result.
def trimMonoid = new Monoid[String] {
def op(a1: String, a2: String) = a1.trim + " " + a2.trim
val zero = ""
}
这是测试幺半群的正确方法吗?这是函数签名,但我不确定如何用我所拥有的实现:def trimMonoid(s: String): Monoid[String]
.
object MonoidTesting {
def main(args: Array[String]) = {
val words = List("Hic", "Est", "Barbarus")
val res = trimMonoid.op( ("Hic"), (trimMonoid.op("est ", "chorda ")) )
println("res : " + res)
assert(res == "Hic est chorda")
println("success")
}
}