gpt4 book ai didi

scala - 在Scala中将方法提取到独立函数

转载 作者:行者123 更新时间:2023-12-04 16:11:45 25 4
gpt4 key购买 nike

给出类似的东西:

class A {
def f(x: X) = ...
def g(y: Y, z: Z) = ...
...
}

如何(自动)提取函数:
object A {
val f' = (a: A, x: X) => a.f(x) // do this automagically for any arbitrary f
val g' = (a: A, y: Y, z: Z) => a.g(y, z) // and deal with arity > 1 too
...
}

有了这个 精确类型签名(首先是对象,然后是参数列表)。让我把问题说得很清楚:

"Given a method f(x1: X1, ..., xn: Xn) defined in the context of a class A, how to automatically extract a function f' that (i) receives an instance a of type A, and (ii) a parameter list that corresponds 1:1 to the parameter list of f, viz. x1: X, ...
xn: Xn
, which implementation is exactly a.f(x1: X1, ..., xn: Xn)"



甚至:

Capturing the concept of extensionality of lambda-calculus, such that you automatically extract an λx.(f x) from f whenever x does not appear free in f.



这首先可以通过找到访问标识符 f 的方法来解决。 , g , ... 没有特定的 a: A (当然,稍后会有一个特定的 A)。我们可以简单地写 f'g'手工,但让我们沉迷于干燥。

附言如果没有运行时反射,这可能是不可能的(尽管使用 Scala 2.10+ 宏可能是可能的),因为我似乎无法找到一种方法来引用 f 的标识符或 g事先没有特定实例( a: A )。但这将类似于以下内容,而不必求助于 strings :
A.getMethod("f"): Function2[A, X, ...]

我也意识到这个问题的实际用途可能会帮助参与者提出替代方案,但我是在抽象意义上讨论这个问题的。我不是要解决我已经简化为这个问题的其他问题。我想知道是否 这个是可能的:-) 这是一个 very nice article真正理解这个问题背后的动机,对 Scala 上的 Eta 扩展的咆哮。

最佳答案

你当然可以在编译时用宏来做到这一点——我在 the preview release of ScalaMock 3 中做了类似的事情。 - 模拟对象是匿名类的实例,其中每个成员都由模拟函数的实例实现。您很可能可以将其用作您正在尝试做的事情的起点。

警告 :ScalaMock 3 目前仅适用于 Scala 2.10.0-M6。它不适用于 M7 或当前的开发版本,因为我还没有(还!)有机会解决宏 API 中的重大更改。

关于scala - 在Scala中将方法提取到独立函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12768300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com