【问题标题】:Scala "Sentence-Like" Function Definition [duplicate]Scala“Sentence-Like”函数定义[重复]
【发布时间】:2015-08-27 15:50:08
【问题描述】:

我正在重构一些代码,并想了解如何编写 Scala 方法,以便可以将它们编写为:

foo = Map("Hello" -> 1)
foo contains "Hello"

“包含”是我想要效仿的风格。这是我正在重构的代码(来自 exercism.io):

class Bob {
  def hey(statement:String): String = statement match {
    case x if isSilent(x)  => "Fine. Be that way!"
    case x if shouting(x) => "Whoa, chill out!"
    case x if asking(x) => "Sure."
    case _ => "Whatever."
  }

  def isSilent2:String => Boolean = _.trim.isEmpty

  def isSilent (str:String) = str.trim.isEmpty

  def shouting(str:String): Boolean = str.toUpperCase == str && str.toLowerCase != str

  def asking(str:String): Boolean = str.endsWith("?")

}

理想情况下,我想让我的 isSilent、喊叫和询问函数都能够以这种风格编写,以便我可以编写:

case x if isSilent x => ...

感谢您的帮助!此外,知道这在 Scala(和其他函数式语言,因为我认为 Haskell 有类似的东西)中被称为什么会非常有帮助,因为我已经做了很多搜索并且找不到我想要描述的内容。

【问题讨论】:

    标签: function scala styles


    【解决方案1】:

    这被称为Infix Notation,只要你有一个单一的参数函数,它就不需要任何特殊的东西。

    它不适合您的原因是您需要调用其方法的对象。以下编译:

    class Bob {
      def hey(statement:String): String = statement match {
        case x if this isSilent x  => "Fine. Be that way!"
        case x if this shouting x  => "Whoa, chill out!"
        case x if this asking x => "Sure."
        case _ => "Whatever."
      }
    
      def isSilent2:String => Boolean = _.trim.isEmpty
    
      def isSilent (str:String) = str.trim.isEmpty
    
      def shouting(str:String): Boolean = str.toUpperCase == str && str.toLowerCase != str
    
      def asking(str:String): Boolean = str.endsWith("?")
    
    }
    

    【讨论】:

    • 哇!多么简单的修复。为了这样一个简单的解决方案,进行了如此多的搜索工作,blech!非常感谢安吉洛。
    • 不客气,但通常不鼓励“谢谢”cmets 这样做:) meta.stackexchange.com/questions/126180/…
    猜你喜欢
    • 2014-08-28
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2021-06-25
    • 2014-05-18
    • 2014-02-15
    相关资源
    最近更新 更多