Collecting nodes

11 views
Skip to first unread message

Malte Schwerhoff

unread,
Dec 16, 2011, 10:58:58 AM12/16/11
to kiama
Hi all,

given an AST I need to collect all nodes of a given type and store
them in a list. After having a look at kiama/rewriting/
RewriterTests.scala (test "counting all terms using queryf") I decided
to go with the following

var fs = List[Foo]();

val collectFoos = everywhere(queryf{
case f: Foo => fs += f
case _ => ()
})

However, RewriterTests.scala has at least one other example which - I
assume - could be adopted for my purpose. Hence my question: What
would be the best/most idiomatic way of doing this?
Is it possible to have a function from Node => Set[Node] that can be
applied to the tree, so that one doesn't need the outer variable fs
that is populated during the traversal?

Thanks,
Malte

Tony Sloane

unread,
Dec 19, 2011, 1:32:05 AM12/19/11
to ki...@googlegroups.com

It's probably better to use the collectl (for list) or collects (for set) strategies in the library, since they encapsulate the collection etc. They are both built on a general collect strategy that uses everywhere (query (...)) as in your code. It uses some magic from the Scala collection library so that it is generic in the collection type.

For example, assuming

case class Var (name : String)

then

collects { case Var (s) => s }

is a strategy that when applied to a tree returns a set of the strings occurring in any Var node in that tree.

cheers,
Tony

Reply all
Reply to author
Forward
0 new messages