How to use ? ? ? for an anonymous function

More vague understanding of ???

Is there a way to replace the functions pair => pair._1 and pair => pair._2 with ??? in the following code and have the code still compile?

  def makeAdjDirected[V](edges: Seq[(V,V)]):Map[V,Set[V]] = {
    edges.groupBy(pair => pair._1)
      .map{case (src, edges) =>
        val destinations = edges.map(pair => pair._2)
        src -> destinations.toSet
      }
  }

When I do a straightforward replacement I get a compilation error:

missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: ((?, Seq[(V, V)])) => ?
      .map{case (src, edges) =>

in

  def makeAdjDirected[V](edges: Seq[(V,V)]):Map[V,Set[V]] = {
    edges.groupBy(???)
      .map{case (src, edges) =>
        val destinations = edges.map(???)
        src -> destinations.toSet
      }
  }

You may hint at the types like: groupBy(??? : (V, V) => V) which will provide students with more information (not sure if you would find that good or bad).

2 Likes

You can explicitly specify the type parameters to groupBy and map that would otherwise be inferred through the function argument’s return type. You can also avoid one intermediate collection by using view and to.

def makeAdjDirected[V](edges: Seq[(V,V)]):Map[V,Set[V]] = {
  edges.groupBy[V](???).map { case (src, edges) =>
    val destinations = edges.view.map[V](???).to(Set)
    src -> destinations
  }
}
1 Like