【问题标题】:In Scala how to curry existing function with single argument and pass to a higher order function?在 Scala 中,如何使用单个参数对现有函数进行 curry 并传递给更高阶函数?
【发布时间】:2013-12-22 09:43:49
【问题描述】:

我有一个函数

def myInnerFunc(a: Int): Int = a

现在我想将它传递给一个高阶函数,并且我希望它传递给使用参数预初始化的高阶函数,因此需要首先使用正确的参数调用我的内部函数,然后我才能将它传递给高阶函数,组成如下:

def myHigherOrderFunction(func: Int => Int): Int = {
  func()
}

所以我需要完成以下代码

myInnerFunc(1) // hmm fix this will actually call my innner function I just want to preinitialize it with one.
func() // didn't work for me how do i run my preinitialized with argument func Int => Int 
  1. 如何在不运行的情况下使用参数 1 预初始化 myInnerFunc?
  2. 如何在高阶函数中运行 func()?

我不知道该怎么做,也找不到相关的文档,谁能提供一个例子? (我看到的所有例子都有多个参数,我只有一个)

【问题讨论】:

    标签: scala functional-programming currying higher-order-functions


    【解决方案1】:

    如果您只是想通过将 f 包装在另一个函数中来以某种方式延迟对 f 的评估,您可以使用匿名函数:

    val outer = { () => f(1) }

    单参数柯里化不那么频繁的原因是,鉴于没有副作用,这会产生一个常数,这不是那么令人兴奋或有用。

    【讨论】:

    • 这不会延迟评估。
    【解决方案2】:

    让我们以相反的顺序回答您的问题:

    如何在高阶函数中运行 func()?

    如果参数已经提供,则不再需要它,所以myHigherOrderFunction 应该如下所示:

    def myHigherOrderFunction(func: Unit => Int): Int = { func() }
    

    如何在不运行的情况下使用参数 1 预初始化 myInnerFunc?

    所以你需要Unit => Int类型的东西。

    val thunk: Unit => Int = { _ => myInnerFunc(argument) }
    

    【讨论】:

      猜你喜欢
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 2017-06-16
      相关资源
      最近更新 更多