Daniel
Daniel

Reputation: 6039

Scala: converting `Map` of functions, to function of `Map`s

Consider the following map, with functions in its value:

val mapOfFunctions: Map[Symbol, T => String] = ... 

I can reverse the order of the functions and the Map:

val functionOfMap: (T) => Map[Symbol, String] = (t: T) => mapOfFunctions.mapValues(f => f(t))

The question is, how to write inverse of this function. Specifically, fill out the following function:

def functionOfMapToMapOfFunction(fun: (T) => collection.Map[Symbol, String]): Map[Symbol, T => String] = {
  // fill me out! 
}

Side note: here I am making the assumption that the input to functionOfMapToMapOfFunction are proper ( they are convertible to MapOfFunctions )

Upvotes: 1

Views: 83

Answers (1)

ayvango
ayvango

Reputation: 5977

T => Map[Symbol,String] may be arbitrary function. It may return map with 0 elements, or with 10 elements, or over 9999 elements. And you would like to build fully defined map with fixed number of elements. So, no way.

But if you could retrieve key set somehow, there is no problem in building Map from it.

def reverseMap(fun : T => Map[Symbol, String], keys : Set[Symbol]) : Map[Symbol, Option[String]] =
  keys.map( k => (k, (t : T) => fun(t).get(k)) ).toMap

Upvotes: 1

Related Questions