加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Scala中提取独立函数的方法

发布时间:2020-12-16 18:46:37 所属栏目:安全 来源:网络整理
导读:给出如下内容: 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
给出如下内容:

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宏),因为我似乎无法找到一种方法来在没有特定实例(a:A)的情况下引用f或g的标识符.但它会像下面这样,而不必求助于字符串:

A.getMethod("f"): Function2[A,X,...]

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

解决方法

你当然可以在编译时使用宏来做这件事 – 我在 the preview release of ScalaMock 3中做了类似的事情 – 模拟对象是匿名类的实例,其中每个成员都是由mock函数的实例实现的.你很可能将它作为你想要做的事情的起点.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读