【问题标题】:Partially applied Function2 with first and second argument部分应用具有第一个和第二个参数的 Function2
【发布时间】:2014-02-11 12:09:21
【问题描述】:

给定一个方法

def f(a: String, b: String) = ???

我想同时获得部分应用的函数(第一个参数和第二个参数)。

我写了以下代码:

def fst = f _ curried "a"
def snd = (s: String) => (f _ curried)(s)("b")

有没有更好的办法?

[update] snd 可以写得更短 def snd = (f _ curried)((_: String))("b")

【问题讨论】:

    标签: scala currying


    【解决方案1】:

    这个比较简单:

    def fst = f("a", (_: String))
    def snd = f((_: String), "b")
    

    但请注意,它会在每次调用时重新计算部分应用的函数,因此在大多数情况下,我更喜欢val(或者可能是lazy val)而不是def

    【讨论】:

    • error: missing parameter type for expanded function ((x$1) => f("a", x$1))
    • @Yaroslav 谢谢,已修复。
    【解决方案2】:

    另一种方法是使用多个参数列表:

    def f(a: String)(b: String) = ???
    

    没有提供参数:

    def fst = f _
    

    提供的第一个参数:

    def fst = f("a")
    

    仅提供第二个参数:

    def fst = f(_: String)("b")
    

    提供的所有参数:

    def snd = f("a")("b")
    

    如果您以与定义相同的顺序对 args 进行柯里化,则此语法比问题中使用的语法更简洁。

    【讨论】:

      猜你喜欢
      • 2019-01-14
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 2019-01-22
      相关资源
      最近更新 更多