记录 Scala 2.10 宏

编程入门 行业动态 更新时间:2024-10-28 00:27:19
本文介绍了记录 Scala 2.10 宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我将从一个例子开始.这是 Scala 2.10 中作为宏的元组的 List.fill 的等价物:

I'll start with an example. Here's an equivalent of List.fill for tuples as a macro in Scala 2.10:

import scala.language.experimental.macros import scala.reflect.macros.Context object TupleExample { def fill[A](arity: Int)(a: A): Product = macro fill_impl[A] def fill_impl[A](c: Context)(arity: c.Expr[Int])(a: c.Expr[A]) = { import c.universe._ arity.tree match { case Literal(Constant(n: Int)) if n < 23 => c.Expr( Apply( Select(Ident("Tuple" + n.toString), "apply"), List.fill(n)(a.tree) ) ) case _ => c.abort( c.enclosingPosition, "Desired arity must be a compile-time constant less than 23!" ) } } }

我们可以这样使用这个方法:

We can use this method as follows:

scala> TupleExample.fill(3)("hello") res0: (String, String, String) = (hello,hello,hello)

这家伙在某些方面是一只奇怪的鸟.首先,arity 参数必须是文字整数,因为我们需要在编译时使用它.在以前版本的 Scala 中,方法(据我所知)甚至无法判断其参数之一是否为编译时文字.

This guy is a weird bird in a couple of respects. First, the arity argument must be a literal integer, since we need to use it at compile time. In previous versions of Scala there was no way (as far as I know) for a method even to tell whether one of its arguments was a compile-time literal or not.

其次,Product返回类型是个谎言——静态返回类型将包括由参数确定的具体元数和元素类型,如上所示.

Second, the Product return type is a lie—the static return type will include the specific arity and element type determined by the arguments, as shown above.

那么我将如何记录这件事呢?在这一点上,我并不期待 Scaladoc 支持,但我想了解一些约定或最佳实践(不仅仅是确保编译时错误消息清晰),这将使运行到宏方法中——使用它的潜在的奇怪需求——对于 Scala 2.10 库的用户来说并不奇怪.

So how would I document this thing? I'm not expecting Scaladoc support at this point, but I'd like to have a sense of conventions or best practices (beyond just making sure the compile-time error messages are clear) that would make running into a macro method—with its potentially bizarre demands—less surprising for users of a Scala 2.10 library.

新宏系统最成熟的演示(例如,ScalaMock、Slick,其他列出 here) 在方法级别上仍然相对没有记录.任何示例或指针都将不胜感激,包括来自具有类似宏系统的其他语言的示例或指针.

The most mature demonstrations of the new macro system (e.g., ScalaMock, Slick, the others listed here) are still relatively undocumented at the method level. Any examples or pointers would be appreciated, including ones from other languages with similar macro systems.

推荐答案

我认为记录这些的最好方法是使用示例代码,正如 Miles 在他的实验中所做的那样 无形的基于宏的分支.

I think the best way to document these is with example code, as Miles has been doing in his experimental macro based branch of shapeless.

更多推荐

记录 Scala 2.10 宏

本文发布于:2023-11-25 18:29:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630858.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!