好吧所以我不知道这是否可行,但是我们说我们有以下列表:
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
是“累加器”(它被初始化为List[Int]()
)并且将针对列表的每个项目更新(或不更新)。和b
如果当前正在处理的列表的新项目。
顺便说一句,这个例子是列表上的(非效率)distinct
。
List(1, 2, 3, 1).distinct.map (n => n*n)
// res163: List[Int] = List(1, 4, 9)
此代码删除重复项,然后以自我文档,简短的方式执行映射。
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