scala:使用 curry 修复参数的值
落叶无声
阅读:85
2025-04-02 23:11:03
评论:0
我有以下功能
scala> def f1 = (prefix: String) => prefix + ".field"
f1: String => java.lang.String
我想从 f1 定义另一个函数,将 prefix 的值固定为 p1,就像这样
def f2: () => String = () => f1("p1")
或更短时间
def f2 = () => f1("p1")
我认为同样可以使用 Function.curried 或 f.curried 和部分应用函数来实现,但我仍然做不到...
--
看看this article我找到了一种更详细的定义方式。我想上面的语法对于这种较长的形式来说只是 suger...
scala> object f2 extends Function0[String] {
| override def apply = f1("p1")
| }
defined module f2
scala> f2
res37: f2.type = <function0>
scala> f2()
res38: java.lang.String = p1.field
请您参考如下方法:
您只能“套用”具有多个参数的函数。至少使用 Scala 默认提供的方法。使用两个参数,它的工作方式如下:
val f2 = (prefix: String, foo:String) => prefix + ".field"
val f1 = f2.curried("p1")
如果你想对 Function1
做同样的事情,你可以“拉皮条”这个类来添加一个新方法:
implicit def addCurry[A,B](f:Function[A,B]) = new Function1WithCurried(f)
class Function1WithCurried[-A,+B](f:Function1[A,B]) {
def curried:Function1[A,Function0[B]] = (x:A) => { () => f(x) }
}
def f1 = (prefix: String) => prefix + ".field"
val f0 = f1.curried
val f2 = f1.curried("p1")
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。