Skip to content

Instantly share code, notes, and snippets.

@chilang
Created December 4, 2010 14:38
Show Gist options
  • Save chilang/728223 to your computer and use it in GitHub Desktop.
Save chilang/728223 to your computer and use it in GitHub Desktop.
Tiny DSL for describing flows
package graphflow
import org.specs.Specification
class Graph {
val nodes:scala.collection.mutable.Set[flow.Node] =
new scala.collection.mutable.HashSet[flow.Node]()
val edges:scala.collection.mutable.Set[flow.Connection] =
new scala.collection.mutable.HashSet[flow.Connection]()
override def toString = "nodes:"+nodes.toString + "\nedges:"+edges.toString
}
object flow {
private val IN = "_in_"
private val OUT = "_out_"
case class Connection(from:Output, to:Input)(implicit g:Graph) {
if (!g.edges.contains(this)) {
g.edges.add(this)
}
override def toString = from.toString + "-->" + to.toString
}
case class Input(node:Node, endpoint:Endpoint) {
override def toString = endpoint+"-|"+node
}
case class Output(node:Node, endpoint:Endpoint) {
def -->(input:Input)(implicit g:Graph) = Connection(this, input)
def -->(node:Node)(implicit g:Graph) = Connection(this, Input(node, IN))
override def toString = node+"|-"+endpoint
}
case class Node(name:String) {
def |-(endpoint:Endpoint):Output = Output(this, endpoint)
def -->(node:Node)(implicit g:Graph) = Connection(Output(this, OUT), Input(node, IN))
def -->(input:Input)(implicit g:Graph) = Connection(Output(this, OUT), input)
override def toString = name
}
case class Endpoint(name:String) {
def -|(node:Node) = Input(node, this)
override def toString = name
}
implicit def string2Endpoint(s:String):Endpoint = Endpoint(s)
implicit def string2Node(s:String)(implicit g:Graph):Node = {
val n = Node(s)
if (!g.nodes.contains(n)) {
g.nodes.add(n)
}
return n
}
}
import flow._
object FlowSpec extends Specification {
"a->b" should {
implicit val g = new Graph
val a = Node("a")
val b = Node("b")
val x = (a|-"x") --> ("y"-|b)
val x_1 = "a"-->"b"
val x_2 = ("a")-->("b")
val x_3 = "a"-->("y"-|b)
val x_4 = ("a"|-"x") --> ("y"-|"b")
val x_5 = ("a"|-"x") --> "b"
println(g)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment