在 Scala 中的压缩列表上使用地图时类型不匹配
Type mismatch when using map on a zipped list in Scala
考虑这段代码:
/** Takes a list and turns it into an infinite looping stream. */
def loop(l: List[Char]): LazyList[Char] = {
l.to(LazyList) #:::loop(l)
}
/** Encodes a sequence of characters with a looped key. */
def codec(message: Seq[Char], key: Seq[Char], cipher: (Char, Char) => Char): Seq[Char] = {
val loopedKey = loop(key.toList)
val mergedMessage = message.toList zip loopedKey
val xorResult = mergedMessage.map(cipher)
xorResult.toSeq
}
循环函数是正确的,但是名为codec
的函数在编译时会产生以下错误:
[error] type mismatch;
[error] found : (Char, Char) => Char
[error] required: ((Char, Char)) => ?
[error] val xorResult = mergedMessage.map(cipher)
我不明白为什么 required
部分说:((Char, Char)) => ?
.
(Char, Char) => Char
是一个接受 2 Chars
并返回 Char
而 zip
will result in a collection of tuples (Char, Char)
的函数。一种选择是更改 cipher
类型以接受元组 - ((Char, Char)) => Char
:
def codec(message: Seq[Char], key: Seq[Char], cipher: ((Char, Char)) => Char): Seq[Char] = ...
不更改签名 - 直接访问元组元素:
val xorResult = mergedMessage.map(t => cipher(t._1, t._2))
或者直接使用tupled
:
val xorResult = mergedMessage.map(cipher.tupled)
考虑这段代码:
/** Takes a list and turns it into an infinite looping stream. */
def loop(l: List[Char]): LazyList[Char] = {
l.to(LazyList) #:::loop(l)
}
/** Encodes a sequence of characters with a looped key. */
def codec(message: Seq[Char], key: Seq[Char], cipher: (Char, Char) => Char): Seq[Char] = {
val loopedKey = loop(key.toList)
val mergedMessage = message.toList zip loopedKey
val xorResult = mergedMessage.map(cipher)
xorResult.toSeq
}
循环函数是正确的,但是名为codec
的函数在编译时会产生以下错误:
[error] type mismatch;
[error] found : (Char, Char) => Char
[error] required: ((Char, Char)) => ?
[error] val xorResult = mergedMessage.map(cipher)
我不明白为什么 required
部分说:((Char, Char)) => ?
.
(Char, Char) => Char
是一个接受 2 Chars
并返回 Char
而 zip
will result in a collection of tuples (Char, Char)
的函数。一种选择是更改 cipher
类型以接受元组 - ((Char, Char)) => Char
:
def codec(message: Seq[Char], key: Seq[Char], cipher: ((Char, Char)) => Char): Seq[Char] = ...
不更改签名 - 直接访问元组元素:
val xorResult = mergedMessage.map(t => cipher(t._1, t._2))
或者直接使用tupled
:
val xorResult = mergedMessage.map(cipher.tupled)