下面的代码将一个字符串转换成它的二进制表示,所以
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
编码 :
import scala.collection.immutable.HashMap
object BinaryRepFunctional extends Application {
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))
}
这是 mapValues 的签名:
override def mapValues[C](f: B => C): Map[A, C] =
new MappedValues(f) with DefaultMap[A, C]
这是 Map 的签名,因此它接受一个函数参数并将这个函数应用于被调用的集合中的每个条目。
def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
def builder = { // extracted to keep method size under 35 bytes, so that it can be JIT-inlined
val b = bf(repr)
b.sizeHint(this)
b
}
val b = builder
for (x <- this) b += f(x)
b.result
}
函数 getBinaryRepresentation 是否可以更明确,因为我很难理解它是如何工作的?