Scala 修剪的幺半群&;在单词之间添加空格

Scala 修剪的幺半群&;在单词之间添加空格,scala,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)

我如何尝试实施下面的练习

// 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 trimmonid(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")
  }
}

Monoid
的一个用例在
fold
中。我猜在Scala中,您可以使用foldLeft和foldRight在字符串列表中测试它

val res = words.foldLeft(trimMonoid.zero)(trimMonoid.op _)

我不确定您的
trimmonid
是否正确执行了练习要求的操作,但无论如何,如果它是用于测试的,那么您可以通过以下方式更好地测试它:

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

为了防止你错过它,作者为所有练习提供了提示和解决方案。