gpt4 book ai didi

scala - 如何在Scala中获得函数名称?

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

考虑一个简单的任务。只需显示整个表达式即可:

    a operator b = c

在Common Lisp中,它可能看起来像这样:
    (defun applyOp (a b op) 
(format t "~S ~S ~S = ~S" a op b (apply op (list a b))))

$ (applyOp 1 2 #'logand)
1 #<FUNCTION LOGAND> 2 = 0

在Scala中,看起来并不那么琐碎:
    def applyOperator(x: Int, y: Int, op: (Int, Int) => Int) = { 
println(x + s" $op " + y + " = " + op(x,y))
}

scala> applyOperator(1, 2, _ & _)
1 <function2> 2 = 0 // how to get the function name?
<function2>的名字是什么?

最佳答案

另一个功能齐全的方法是简单的macro

假设您编写了最简单的宏来提取表达式和类型名的字符串表示形式:

import scala.reflect.macros.blackbox.Context
import scala.language.experimental.macros

class VerboseImpl(val c: Context) {
import c.universe._

def describe[T: c.WeakTypeTag](expr: c.Expr[T]): c.Expr[(String, String, T)] = {
val repr = expr.tree.toString
val typeName = weakTypeOf[T].toString
c.Expr[(String, String, T)](q"($repr, $typeName, $expr)")
}

}

object Verbose{
def apply[T](expr: T): (String, String, T) = macro VerboseImpl.describe[T]
}

接下来,您可以在另一个源中(最好在另一个子项目中)编写
val a = 2
val b = 3
println(Verbose(a + b + 3))

看看魔术串
(a.+(b).+(3),Int,8)

从这一点出发,您可以增强宏以显示有关方法,参数,类型等的任何信息。

请注意,宏是在编译时评估的。因此 Verbose.apply调用的开销就像用两个字符串常量创建元组,因此,尽管这是唯一的不重复,可扩展的方法,但它绝对是性能最高的

关于scala - 如何在Scala中获得函数名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33790311/

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