toOuterNodes is a Traversable but acts as a Set

15 views
Skip to first unread message

alex

unread,
Mar 15, 2018, 9:34:04 AM3/15/18
to scala-graph
I found this beheaviour rather puzzling. My setup is the following:
  • my nodes are custom objects that have a "weight: Int" field.
  • I want to get a list of all the weights in my graph g , so i do g.toOuterNodes.map(_.weight)

The result of this line is a Traversable that contains the weights of my nodes, but if multiple nodes have the same weight, it will contain the weight only once!

This gives very counter-intuitive beheaviour such as "g.toOuterNodes.map(_.weight).size != g.toOuterNodes.size". To get the result I want, I had to do

g.toOuterNodes.toVector.map(_.weight).


I understand that the nodes of the graph form a set, but since ".toOuterNodes" offers a "Traversable" trait and not a "Set" trait, it would make sense for it

to accept multiple instances of the same object.

Peter Empen

unread,
Mar 18, 2018, 4:49:16 AM3/18/18
to scala-graph
Alex,

you are right in that g.toOuterNodes is not working as you'd expect. However, this method is primarily meant for internal usage so, based on your feedback, its visibility need be limited.
Your friend is g.nodes.toOuter instead.

To your specific issue: Having a set like
val set = Set((1, 2), (1, 3))

it is map's intended behavior to return another set. Thus
set map (_._1)

will have one element. So, most efficiently since toIterator is lazy, you should do
set.toIterator map (_._1)

Peter

alex

unread,
Mar 18, 2018, 5:16:16 AM3/18/18
to scala-graph
Thank you for the clear reply :)

Peter Empen

unread,
Mar 18, 2018, 8:09:30 AM3/18/18
to scala-graph
You are welcome.
One more point: you can also go directly with the node set like
g.nodes.toIterator.map(_.weight)
what is the same as
g.nodes.toIterator.map(_.value.weight)

Reply all
Reply to author
Forward
0 new messages