第一个代码是我对网络练习的第一个解决方案,它工作正常(通过所有测试),但有很多重复的代码。 所以我开始抽象函数,我得到了第二个项目,我认为它应该同样有效,但它没有(它只是传递了一些),我做错了什么?
1)
class Anagram(strg: String) {
def matches(words: Seq[String]): Seq[String] = {
def stylisticDifference(things: Seq[String], text: String): Seq[String] = {
things.filter(w => w.toLowerCase == text.toLowerCase)
}
def essensialSimlitude(things: Seq[String], text: String):Seq[String] = {
things.filter(w => w.toLowerCase.sorted == text.toLowerCase.sorted)
}
essensialSimlitude(words,strg) diff stylisticDifference(words,strg)
}
}
2)
class Anagram(strg: String) {
def matches(words: Seq[String]):Seq[String] = {
def answer(things: Seq[String], text: String, fn: String => String): Seq[String] = {
things.filter(w => fn(w.toLowerCase) == fn(text.toLowerCase))
}
val stringSort = (s: String) => s.sorted
answer(words,strg, identity) diff answer(words, strg, stringSort)
}
}
答案 0 :(得分:0)
我的猜测:
更改此
answer(words,strg, identity) diff answer(words, strg, stringSort)
到此:
answer(words,strg, stringSort) diff answer(words, strg, identity)
说明:
http://alvinalexander.com/scala/union-intersection-difference-scala-sets
数学上的差异不是可交换的。