Something that I still find difficult and confusing in Scala, even after using the language for almost 3 years, is the distinction between Array and other sequences. Yes, I understand that Array
is optimized so that it can use the java native arrays, which is excellent for execution speed.
However, it is a reasonable desire that a user wants to write a function which accepts an Array
or a List
, and within the function, perform operations which are valid for Array
and List
, such as foldLeft
. I don’t think it is reasonable to expect a programmer to be able to implement a type class to allow this.
What is the correct way to write the following 2 functions without code duplication. BTW IntelliJ also warns me that the code is duplicated.
def makeAdj[A](edges:List[(A,A)]):Map[A,Set[A]] = {
edges.foldLeft(Map[A,Set[A]]()){
case (adj,(src,dst)) =>
adj + (src -> (adj.getOrElse(src,Set())+dst))
}
}
def makeAdj[A](edges:Array[(A,A)]):Map[A,Set[A]] = {
edges.foldLeft(Map[A,Set[A]]()){
case (adj,(src,dst)) =>
adj + (src -> (adj.getOrElse(src,Set[A]())+dst))
}
}
I’d like to write the following, but it’s wrong.
def makeAdj[M[_]<:Foldable[_],A](edges:M[(A,A)]):Map[A,Set[A]] = {
edges.foldLeft(Map[A,Set[A]]()){
case (adj,(src,dst)) =>
adj + (src -> (adj.getOrElse(src,Set())+dst))
}
}