2013-10-22 92 views
0

我如何嘗試執行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 = "" 
} 

這是測試monoid的正確方法嗎?這是函數簽名,但我不確定如何使用我的實現: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

萬一你錯過了,筆者有一個[GitHub的倉庫(https://github.com/pchiusano/fpinscala)與所有的練習提示與解決方法。 –

回答

1

之一的Monoid用例是在fold。我在斯卡拉猜你有foldLeft和foldRight,你可以用它來測試它串名單上

val res = words.foldLeft(trimMonoid.zero)(trimMonoid.op _) 
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 
相關問題