Scala 检查映射中的值
Scala check value inside mapping
好吧,我不知道这是否可行,但假设我们有以下列表:
List(1, 2, 3, 1)
如果我想在上面应用地图,有没有办法让我检查我之前是否已经有一个值,例如在第 4 个值(第 2 个 1)上,它会说它已经遇到了 1,然后抛出错误或其他东西。
这将是 foldLeft
阶段的作用:
List(1, 2, 3, 1).foldLeft(List[Int]()) {
// The item has already been encountered:
case (uniqueItems, b) if uniqueItems.contains(b) => {
// If as stated, you want to throw an exception, that's where you could do it
uniqueItems
}
// New item not seen yet:
case (uniqueItems, b) => uniqueItems :+ b
}
foldLeft 在工作时遍历一个序列(在每个新元素处),结果基于之前的结果。
对于每个元素,模式匹配(uniqueItems, b)
应该这样理解:uniqueItems
是"accumulator"(它被初始化为List[Int]()
)并且会被更新(或不)对于列表中的每个项目。并且 b
如果当前正在处理列表的新项目。
顺便说一句,这个例子是一个 (non-efficient) distinct
在一个列表上。
fold
可能是要走的路。问题是每次迭代都必须携带先前元素的内存以及正在构建的 map()
结果。
List(1, 2, 3, 11).foldRight((Set[Int](),List[String]())) {case (i, (st, lst)) =>
if (st(i)) throw new Error //duplicate encountered
else (st + i, i.toString :: lst) //add to memory and map result
}._2 //pull the map result from the tuple
List(1, 2, 3, 1).distinct.map (n => n*n)
// res163: List[Int] = List(1, 4, 9)
此代码删除重复项,然后以自我记录的简短方式执行映射。
好吧,我不知道这是否可行,但假设我们有以下列表:
List(1, 2, 3, 1)
如果我想在上面应用地图,有没有办法让我检查我之前是否已经有一个值,例如在第 4 个值(第 2 个 1)上,它会说它已经遇到了 1,然后抛出错误或其他东西。
这将是 foldLeft
阶段的作用:
List(1, 2, 3, 1).foldLeft(List[Int]()) {
// The item has already been encountered:
case (uniqueItems, b) if uniqueItems.contains(b) => {
// If as stated, you want to throw an exception, that's where you could do it
uniqueItems
}
// New item not seen yet:
case (uniqueItems, b) => uniqueItems :+ b
}
foldLeft 在工作时遍历一个序列(在每个新元素处),结果基于之前的结果。
对于每个元素,模式匹配(uniqueItems, b)
应该这样理解:uniqueItems
是"accumulator"(它被初始化为List[Int]()
)并且会被更新(或不)对于列表中的每个项目。并且 b
如果当前正在处理列表的新项目。
顺便说一句,这个例子是一个 (non-efficient) distinct
在一个列表上。
fold
可能是要走的路。问题是每次迭代都必须携带先前元素的内存以及正在构建的 map()
结果。
List(1, 2, 3, 11).foldRight((Set[Int](),List[String]())) {case (i, (st, lst)) =>
if (st(i)) throw new Error //duplicate encountered
else (st + i, i.toString :: lst) //add to memory and map result
}._2 //pull the map result from the tuple
List(1, 2, 3, 1).distinct.map (n => n*n)
// res163: List[Int] = List(1, 4, 9)
此代码删除重复项,然后以自我记录的简短方式执行映射。