list - 考虑到字符串列表代表 Scala 中映射的键,如何将 List[String] 转换为 List[Map[String,String]] ?

标签 list scala recursion maps

我有一个引用文献列表:

val references: List[String]= List("S","R")

我还有变量,它是:

val variables: Map[String,List[String]]=("S"->("a","b"),"R"->("west","east"))

references 是变量映射的键列表。

我想构造一个函数,它需要:

def expandReplacements(references:List[String],variables:Map[String,List[String]]):List[Map(String,String)]

这个函数基本上应该创建返回以下组合

List(Map("S"->"a"),("R"->"west"),Map("S"->"a"),("R"->"east"),Map("S"->"b"),("R"->"west"),Map("S"->"b"),("R"->"east"))

我尝试这样做:

val variables: Map[String,List[String]] = Map("S" -> List("a", "b"), "R" -> List("east", "central"))
val references: List[String] = List("S","R")

def expandReplacements(references: List[String]): List[Map[String, String]] =
  references match {
    case ref :: refs =>
      val variableValues =
        variables(ref)
      val x = variableValues.flatMap { variableValue =>
        val remaining = expandReplacements(refs)
        remaining.map(rem => rem + (ref -> variableValue))
      }
      x

    case Nil => List.empty
  }

最佳答案

如果您有超过 2 个推荐人,您可以执行以下操作:

def expandReplacements(references: List[String], variables :Map[String,List[String]]): List[Map[String, String]] = {
  references match {
    case Nil => List(Map.empty[String, String])
    case x :: xs =>
      variables.get(x).fold {
        expandReplacements(xs, variables)
      } { variableList =>
        for {
          variable <- variableList.map(x -> _)
          otherReplacements <- expandReplacements(xs, variables)
        } yield otherReplacements + variable
      }
  }
}

代码运行于Scastie .

关于list - 考虑到字符串列表代表 Scala 中映射的键,如何将 List[String] 转换为 List[Map[String,String]] ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66352860/

相关文章:

java - 没有选定项目的 SWT 列表

Python 矩阵给出与最后一条记录相同的结果

recursion - 使用 recur 在 Clojure 中缓存 "recursive"调用的值

python - 如何检查元素是否只在python中出现在列表中一次?

java - 同步 Collection 列表

scala - HDFS : java. io.FileNotFoundException : File does not exist: name. _COPYING

scala - 我希望我的函数返回 Stream[T],但我不知道如何进行类型检查

scala - 如何修改由cmd sbt包生成的jar名称

使用递归表达式匹配嵌套大括号的正则表达式?

java - 处理第 k 个最小分区中的重复数字