gpt4 book ai didi

Scala Quasiquote 提升

转载 作者:行者123 更新时间:2023-12-05 01:00:06 24 4
gpt4 key购买 nike

Quasiquotes 的 Scala 文档在解释 Lifting 时提到了这一点:

One can also combine lifting and unquote splicing:


 scala> val ints = List(1, 2, 3)
scala> val f123 = q"f(..$ints)"
f123: universe.Tree = f(1, 2, 3)

scala> val intss = List(List(1, 2, 3), List(4, 5), List(6))
scala> val f123456 = q"f(...$intss)"
f123456: universe.Tree = f(1, 2, 3)(4, 5)(6)



代码示例中的lift vs unquote splicing具体实现在哪里?

最佳答案

在这两个示例中,两者同时发生。

取消引用是替换 Tree 的过程某处进入另一个 Tree 的结构(如插值)。在本例中,ints不完全是 Tree ,但存在一个 Liftable[List[T]]这允许我们取消引用 List[T]Tree ,就好像它是一个 Tree (即 Liftable 告诉编译器如何将这里的文字 List[Int] 转换为 Tree 以便它可以被替换)。

引用文档:

Unquote splicing is a way to unquote a variable number of elements.



这里,可变数量的元素将是 List 中的元素。我们想取消报价。如果我们这样做了 q"f($ints)" ,那么我们将简单地取消引用 ints作为 f 的单个参数.但也许我们想对 f 应用重复的参数反而。为此,我们使用无引号拼接。
q"f(..$ints) // Using `..` means we get f(1, 2, 3) instead of f(List(1, 2, 3))

同样,文档说得最好,真的:

Dots near unquotee annotate degree of flattening and are also called splicing rank. ..$ expects argument to be an Iterable[Tree] and ...$ expects Iterable[Iterable[Tree]].



所以提升允许我们取消引用 List[T]进树 f(x)好像它是一个 Iterable[Tree] ,并且取消引用拼接允许我们取消引用可变数量的元素 List[T]包含为 f 的多个参数.

以下是不同的相关组合:
val listTree = q"scala.collection.immutable.List(1, 2, 3)"
val treeList = List(q"1", q"2", q"3")
val literalList = List(1, 2, 3)

scala> q"f($listTree)" // plain unquoting from another Tree
res6: reflect.runtime.universe.Tree = f(scala.collection.immutable.List(1, 2, 3))

scala> q"f($literalList)" // unquoting from lifting
res7: reflect.runtime.universe.Tree = f(scala.collection.immutable.List(1, 2, 3))

scala> q"f(..$treeList)" // plain unquote splicing
res8: reflect.runtime.universe.Tree = f(1, 2, 3)

scala> q"f(..$literalList)" // unquote splicing and lifting
res9: reflect.runtime.universe.Tree = f(1, 2, 3)

关于Scala Quasiquote 提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30155938/

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