【问题标题】:Higher order functions in scalascala中的高阶函数
【发布时间】:2021-02-01 05:08:37
【问题描述】:

我有这两个功能:

 def replaceValue(value: String): String =
    if (value.startsWith(":")) value.replaceFirst(":", "/") else value

  def getData(value: String): String = {
    val res = replaceValue(value).replace("-", ":")
    val res1    = res.lastIndexOf(":")
    if (res1 != -1) res.substring(0,3)
    else res.concat("-")
  }

我想将它们转换为高阶函数。

到目前为止,我已经尝试过了。 它的高阶函数是什么?

  def getData = (value: String) => {
    val res = replaceValue(value).replace("-", ":")
    val res1    = res.lastIndexOf(":")
    if (res1 != -1) res.substring(0,3)
    else res.concat("-")
  }

【问题讨论】:

  • 您能否详细说明高阶函数是什么意思?你想要一个创建getData 函数的函数吗?
  • 是的。无论如何,我想避免这种情况,如果其他条件如下:def getData =(f:String => String,value:String)然后我可以传递子字符串或concat。我希望这种方法尽可能精确@TomerShetah
  • 或 def getData(value: String) : String => String
  • 那么有没有更好的方法来写这个函数呢?
  • @EatPayBong 我认为您应该弄清楚您要解决的问题,而不是仅仅尝试编写 HOF

标签: scala scala-collections higher-order-functions


【解决方案1】:

您可以执行以下操作:

def getDataImpl(f: String => String)(value: String): String = {
    f(value)
}

def getDataSubstring: String => String = getDataImpl(_.substring(0,3))
def getDataConcat: String => String = getDataImpl(_.concat("-"))

def getData(value: String): String = {
    val replaced = replaceValue(value).replace("-", ":")
    if (replaced.contains(":")) {
        getDataConcat(replaced)
    } else {
        getDataSubstring(replaced)
    }
}

代码运行可以在Scastie找到。

【讨论】:

  • 在我看来这只是一个不必要的函数包装,getDataImpl 没有任何作用
  • 我同意在这个例子中它并没有增加太多。但是在更复杂的情况下,您希望在getDataImpl 中应用相互行为,然后它确实会有所帮助。不要忘记这只是一个小例子,它可以代表一个更复杂的流程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多