如何在"for"理解中添加跟踪? [英] How to add tracing within a 'for' comprehension?
问题描述
对于for
理解中的日志跟踪,我使用了伪分配,如下所示:
For log tracing inside a for
comprehension, I've used dummy assignment like this:
val ll = List(List(1,2),List(1))
for {
outer <- ll
a = Console.println(outer) // Dummy assignment makes it compile
inner <- outer
} yield inner
a =
位似乎很尴尬.有没有更清洁的方法?
The a =
bit seems awkward. Is there a cleaner way?
推荐答案
您始终可以定义自己的trace
函数:
You could always define your own trace
function:
def trace[T](x: T) = {
println(x) // or your favourite logging framework :)
x
}
然后,理解力将如下所示:
Then the for comprehension would look like:
for {
outer <- ll
inner <- trace(outer)
} yield inner
或者,如果您希望打印更多信息,则可以如下定义trace
:
Alternatively, if you want more information printed, you can define trace
as follows:
def trace[T](message: String, x: T) = {
println(message)
x
}
和for理解如下:
for {
outer <- ll
inner <- trace("Value: " + outer, outer)
} yield inner
编辑:是的,您可以编写trace
使其作用在目标的右侧,以回应您的评论!您只需要使用一些隐式技巧即可.实际上,它看起来确实比应用于左侧时好得多:).
In response to your comment, yes, you can write trace
so that it acts to the right of the target! You just have to use a bit of implicit trickery. And actually, it does look much nicer than when applied to the left :).
为此,您必须先定义一个Traceable
类,然后定义对该类的隐式转换:
To do this, you have to first define a class which is Traceable
and then define an implicit conversion to that class:
class Traceable[A](x: A) {
def traced = {
println(x)
x
}
}
implicit def any2Traceable[A](x: A) = new Traceable(x)
然后,您所提供的代码中唯一需要修改的就是将traced
添加到要跟踪的值的末尾.例如:
Then the only thing you have to modify in the code you have provided is to add traced
to the end of the value you want to be traced. For example:
for {
outer <- ll
inner <- outer traced
} yield inner
(Scala编译器将其翻译为outer.traced
)
(this is translated by the Scala compiler into outer.traced
)
这篇关于如何在"for"理解中添加跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!