【问题标题】:Scala Curry-Uncurry A FunctionScala Curry-Uncurry A 函数
【发布时间】:2021-11-29 08:13:07
【问题描述】:

我正在尝试创建一个函数,该函数接收带有 2 个参数的基本 curried 加法器函数并返回 uncurried 加法器函数,反之亦然,用于 scala 中的 currying 函数(接收 uncurried-returns curried)。我很难确定 curried 函数的返回类型,有人可以帮忙吗?

def adderCurried(a: Int)(b: Int): Int = a + b

//define a function that returns uncurried version of this function:

val adderUncurried = toAdderUncurried(adderCurried)

adderUncurried(5,6) // returns 11

def adder(a: Int, b: Int): Int = a + b

//define a function that returns curried version of this function:

val adderCurried = toAdderCurried(adder)

adderCurried(5,6) // returns 11

【问题讨论】:

    标签: scala currying


    【解决方案1】:

    部分问题是您没有正确调用柯里化函数:

    adderCurried(5,6) // too many arguments (found 2, expected 1)
    

    应该以与声明相匹配的方式调用它:

    def adderCurried(a: Int)(b: Int)
    
    adderCurried(5)(6)
    

    这表明这里实际上有两个函数调用。第一次调用(5) 返回一个函数,当使用(6) 调用时会给出答案。第二个函数必须接受Int 并返回Int,所以它是Int => Int,这必须是adderCurried(5) 返回的内容。

    所以adderCurried 接受Int 并返回Int => Int 所以类型是

    Int => (Int => Int)
    

    或者只是

    Int => Int => Int
    

    您可以按如下方式检查:

    val check: Int => Int => Int = adderCurried // OK
    

    您应该能够根据这些类型为toAdderCurriedtoAdderUncurried 创建签名。

    【讨论】:

      【解决方案2】:

      toAdderUncurried 函数会是这样的。

      def toAdderUncurried(f: Int => Int => Int): (Int, Int) => Int = (x, y) => f(x)(y)
      

      你可以这样称呼它。

      toAdderUncurried(adderCurried)(x, y)
      

      而咖喱函数会是这样的。

      def curry(f: (Int, Int) => Int): Int => Int => Int = x => y => f(x, y)
      

      你可以这样称呼它

      curry(toAdderUncurried(adderCurried))(x)(y)
      

      【讨论】:

        【解决方案3】:

        让我添加Tim answer。在这里,您有 2 个加法器功能选项:

        • 咖喱type Curried = (Int => Int => Int)
        • 和非咖喱type Uncurried = (Int, Int) => Int

        你的转换函数的签名应该是这样的:

        def toAdderUncurried(adderCurried: Curried): Uncurried = ???
        def toAdderCurried(adderUncurried: Uncurried): Curried = ???
        

        【讨论】:

          猜你喜欢
          • 2016-08-28
          • 2012-01-13
          • 1970-01-01
          • 1970-01-01
          • 2017-11-15
          • 1970-01-01
          • 2015-06-19
          • 2021-02-16
          • 1970-01-01
          相关资源
          最近更新 更多