Folding a DiGraph with a Node method

29 views
Skip to first unread message

tampler

unread,
Sep 8, 2019, 5:28:56 AM9/8/19
to scala-graph
Hello

I defined a Node like this and create a simple DiGraph, say (1~2~3)
case class MyNode(id: Int, op: Function1[Int, Int])


Now I want to fold the graph with my "op", passing an input to the root node.

valfold = g1.fold(0)(MyNode.op)

The full code is below :

import scalax.collection.Graph
import scalax.collection.GraphEdge._

case class MyNode(id: Int, op: Function1[Int, Int])

case class MyEdge(
  val nodeFrom
: MyNode,
  val nodeTo
: MyNode
) extends DiEdge(NodeProduct(nodeFrom, nodeTo))

object App1 extends Scastie {

  val f
= (_: Int) + 1
  val g
= (_: Int) * 2
  val h
= (_: Int) - 3

  val n1
= MyNode(1, f)
  val n2
= MyNode(2, g)
  val n3
= MyNode(3, h)

  val e1
= MyEdge(n1, n2)
  val e2
= MyEdge(n2, n3)

  val nset
= Set(n1, n2, n3)
  val eset
= Set(e1, e2)
  val g1  
= Graph.from(nset, eset)

   
  println
(g1.isAcyclic)
  println
(g1.isComplete)

  val fold
= g1.fold(0)(MyNode.op)

}



Peter Empen

unread,
Sep 10, 2019, 5:43:36 AM9/10/19
to scala-graph
You can fold the nodes like

g1.nodes.foldLeft(0) { case (cum, n) => cum + n.op(???) }

I inserted ??? because it's not clear what you intend to pass to op.
Message has been deleted

tampler

unread,
Sep 12, 2019, 5:07:01 AM9/12/19
to scala-graph
Hi Peter.

Thanks, that solved my problem

val res = g1.nodes.foldLeft(0) { case (cum, n) => cum + n.op(1) }

works like a charm

Simon Parten

unread,
Jan 24, 2020, 4:37:00 AM1/24/20
to scala-graph
I'm trying to get into scala graph.

I'm not able to get this to compile with scala 2.12.10. I have version 1.13.1.

Val g1 had its type inferred as Graph[MyNode], GraphEdge.Diedge rather than MyEdge.

I'm not clear why though, as eset is a set of MyEdge.

The fold then refuses to compile because it doesn't find op.

Any ideas here? I'll try and upgrade to scala 13.x... But this may not be so easy in my project.

Peter Empen

unread,
Jan 24, 2020, 4:58:12 AM1/24/20
to scala-graph
Simon, what exactly did you try?

Simon Parten

unread,
Jan 24, 2020, 5:19:39 AM1/24/20
to scala-graph
I copied and pasted tamplers code above into a scala worksheet in intellij.

Then, I replaced tamplers fold line, with his final post.

The worksheet refuses to compile it.

If I insert the type annotation using intellij, it claims the type of n is:

GraphPredef.Param[MyNode, DiEdge].

I think its type should be MyNode.

Oh no! I realised I was trying to fold g1...

Not g1.nodes...

Oops - User issue :-)! Problem solved. Thanks for the quick response.

Reply all
Reply to author
Forward
0 new messages