我如何尝试实施Functional Programming in 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")
}
}
答案 0 :(得分:1)
Monoid
的一个用例位于fold
。我想在Scala中你有foldLeft和foldRight可以用来在字符串列表上测试它
val res = words.foldLeft(trimMonoid.zero)(trimMonoid.op _)
答案 1 :(得分:1)
我不确定你的trimMonoid
是否正确地确定了练习所要求的内容,但无论如何,如果它用于测试,那么你可以用这种方式更好地测试它:
scala> val xs = List("hey","hi","hello")
xs: List[String] = List(hey, hi, hello)
scala> xs.foldLeft(trimMonoid.zero)((x,y)=> trimMonoid.op(x,y))
res2: String = hey hi hello