1

I am studying how to implement a graph in scala and what id really like to have is a list of edges (assume already defined), like a List[Edge], but with a few extra methods, for returning all vertices for example. But lists are sealed (final?) And can't be subclassed.

How could I go about this?

object Main {

  implicit def listToGraph(list: List[Edge]): Graph = new Graph(list)

  class Graph(e: List[Edge]) {
    def vertices() = (e.map(_.v1) ++ e.map(_.v2)).distinct
  }

  case class Edge(v1: Long, v2: Long)

  def main(args: Array[String]): Unit = {
    val e: List[Edge] = List(Edge(0, 1), Edge(0, 2))
    e.vertices.foreach(println)
  }
}

This code works -- in the sense that I can call _.vertices on a List[Edge], but what I was really trying to do is have a class named Graph on which I can call any method from List[Edge] and _.vertices

2
  • What happens when you try it? You do realize that you could have tried this in about half the time it took you to write your question, and you would have gotten your answer within a few milliseconds, instead of having to wait for hours. Commented Sep 17, 2016 at 1:13
  • 1
    Not even close to being useful. Commented Sep 17, 2016 at 1:15

1 Answer 1

1

You could model your solution better by implicitly converting from graph to list instead:

case class Edge(v1: Long, v2: Long) 

case class Graph(e: List[Edge]) {
      def vertices() = (e.map(_.v1) ++ e.map(_.v2)).distinct
    } 

implicit def graphToList(graph: Graph): List[Edge] = graph.e 

val g = Graph(List(Edge(0, 1), Edge(0, 2))) 

g.head  // use graph as a list
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.