Function Scala DSL和块作为函数参数
如何在Scala上实现DSL构造Function Scala DSL和块作为函数参数,function,scala,dsl,Function,Scala,Dsl,如何在Scala上实现DSL构造 def objeects(f: => Int):Int { println(f) // ??? evaluate every function, that f contain in the block. } manytimes { 1+1 2+1 3+1 } 结果是,当我们将块传递给该方法时,我们需要对每个函数进行一次计算 9
def objeects(f: => Int):Int {
println(f)
// ??? evaluate every function, that f contain in the block.
}
manytimes {
1+1
2+1
3+1
}
结果是,当我们将块传递给该方法时,我们需要对每个函数进行一次计算
9
您的块是一个函数:
{
1+1 // calculate 2 and throw away
2+1 // calculate 3 and throw away
3+1 // return 4
}
这就是Scala语法的工作原理,您无法更改它。事实上,如果可以的话,在这种情况下你会期望发生什么
manytimes {
val x = 1
val y = 2
x + y
}
意志
对你的目的来说足够好吗?经过几个小时的搜索,我找到了一些非常好的组件,它们可以帮助我解决问题
multifunc {
println(1)
println(2)
}
// output
Expr[c.universe.Tree](func.tree)
scala.this.Predef.println(2) // <-- it my case its the second and last elem
class scala.reflect.internal.Trees$Apply // <-- we can apply it as usual
class scala.reflect.internal.Trees$Block
tree<<
class scala.reflect.internal.Trees$EmptyTree$
<empty>
multifunc{
println(1)
println(2)
}
//输出
Expr[c.universe.Tree](函数树)
scala.this.Predef.println(2)//q”“”
println($正文)
println($body.getClass)
$body
"""
大小写=>q“”
}
println(func.tree.children.last)//我不确定您在这里追求的是什么,但看起来您几乎是在尝试对一系列函数重新进行foldLeft
。。。当然,这不是通用的解决方案,从问题的内容来看,这就是它的样子。我需要很多函数作为参数,比如(arg*表示多个参数,转换为数组),但对于块{1+12+13+1}
中的函数,我认为这(很容易)不可行,但我可能错了,我们看看其他人怎么说。我认为你应该更好地解释你想要完成什么。你的例子中有多少次?你所说的“并集”是什么意思(在你的例子中,它只是和,但编译器应该如何猜测它)?我认为,如果你能描述你想解决的问题,而不是你认为解决问题的方法应该是什么样的(例如,为什么你首先需要这个结构?),会更有帮助。我尝试使用=>Int*
和变体,但它不起作用。我相信@StanislavSobolev需要编写一个宏或重新设计API。但是一些框架和lib提供了带有多个函数的块语法,就像我前面展示的expect{person.name==“Fred”person.age*2==84 person.say(“Hi”,“from”,“Expecty!”)==“Hi from Expecty!”)
在该项目编号中。这是一个由宏分解为单独表达式的布尔块。看到了吗?你能写出分隔表达式的宏示例吗?就在那里:。其他函数也可能对您有用,您可以从第22行开始计算。
multifunc {
println(1)
println(2)
}
// output
Expr[c.universe.Tree](func.tree)
scala.this.Predef.println(2) // <-- it my case its the second and last elem
class scala.reflect.internal.Trees$Apply // <-- we can apply it as usual
class scala.reflect.internal.Trees$Block
tree<<
class scala.reflect.internal.Trees$EmptyTree$
<empty>
def _multifunc [A](c: BlackboxContext)(
func: c.Expr[A]
): c.Expr[Unit] = {
import c.universe._
val tree = func.tree match {
case q"($i: $t) => $body" => q"""
println($body)
println($body.getClass)
$body
"""
case _ => q""
}
println(func.tree.children.last) // <-- accessor to AST children
println(func.tree.children.last.getClass)
println(func.tree.getClass)
println("tree<<")
println(tree.getClass)
println(tree)
c.Expr(tree)
}