以下のコードは、文字列をバイナリ表現に変換します。
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 がどのように機能するかを理解するのが難しいので、関数をより明示的にすることはできますか?