将此迭代解决方案转换为功能解决方案

时间:2013-08-28 21:28:56

标签: scala functional-programming

此类采用[String,List [String]]类型的Map并输出[String,String]的Map 其中键是List的名称,值是字母的二进制表示。 每个数字对应于字母是否出现在列表中。 1 - 它出现,0 - 它没有出现。 例如,此列表:

1 = 1,1,0,0
2 = 1,1,1,0
3 = 1,1,0,1
4 = 1,1,0,0

 Returns

4-->1100
1-->1100
2-->1110
3-->1101

以下是一个迭代解决方案:

object BinaryRep {

  var userDetails : scala.collection.immutable.HashMap[String, List[String]] = new  scala.collection.immutable.HashMap[String, List[String]] 
  var lettersToCheck = List("a" , "b" , "c"  ,"d")
  def main(args: Array[String]) {

    userDetails += "1" -> List("a" , "b")
    userDetails += "2" -> List("a" , "b" , "c")
    userDetails += "3" -> List("a" , "b" , "d")
    userDetails += "4" -> List("a" , "b")

    val binRep = getBinaryRepresentation

    getBinaryRepresentation foreach ( (t2) => println (t2._1 + "-->" + t2._2))

  }

  def getBinaryRepresentation = {

    var mapvalues = new scala.collection.immutable.HashMap[String, String]
    var binaryRep = "";

    for (usd <- userDetails) {
      for (letter <- lettersToCheck) {
        if (usd._2.contains(letter)) {
          binaryRep += "1"
        } else {
          binaryRep += "0";
        }
      }
      mapvalues += usd._1 -> binaryRep
      binaryRep = "";
    }
    mapvalues

  }


}

我认为这是一个非常混乱,但它是我能做的最好的。什么是实现相同结果的更实用的方法?

1 个答案:

答案 0 :(得分:2)

import scala.collection.immutable.HashMap

object BinaryRep {
  val userDetails = HashMap("1" -> "ab",
                            "2" -> "abc",
                            "3" -> "abd",
                            "4" -> "ab")
  val lettersToCheck = "abcd"
  def getBinaryRepresentation = userDetails.mapValues(string => lettersToCheck.map(letter => if (string.contains(letter)) '1' else '0'))

  getBinaryRepresentation foreach ( (t2) => println (t2._1 + "-->" + t2._2))
}
像这样的数据转换几乎总是可以作为一系列map调用来实现。