【问题标题】:Code abstraction in scalascala中的代码抽象
【发布时间】:2017-05-26 10:45:52
【问题描述】:

第一个代码是我对网络练习的第一个草稿解决方案,它运行良好(通过了所有测试),但有很多重复代码。 所以我开始抽象函数,我得到了第二项,我认为它应该同样有效,但它没有(它只是通过了一些),我做错了什么?

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)
  }
}

【问题讨论】:

  • 第二个失败是什么?它应该做什么以及它正在做什么?
  • w => fn(w.toLowerCase) == fn(text.toLowerCase) 更改为 w => fn(w).toLowerCase == fn(text).toLowerCase 。因为sorting then lowercase 结果将不同于lowercase then sorting

标签: scala abstraction higher-order-functions


【解决方案1】:

我的猜测:

改一下

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

数学中的 Diff 不可交换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-01
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 2014-10-27
    • 1970-01-01
    • 2017-01-13
    相关资源
    最近更新 更多