val x = "pizseagtsgevlvwpbshxfwbjijtmslkufgofretehjgpcdedstydokejsnrccnkbruawgjmemfqhwmhjsykrejmmexgrsdlwtaybtnhfcapsylopkthboqkvicgwrvycphqnulnjgfgjlqnhdyfwweyifpxyxrvpnshjrrkmkwrvjjssublanosljhqhppmewuidyqblfcjzkwbhqlljvvcjqthbkpcoquepqzcvbkdlhufbkpiyaqbfblexry"
val y = "pizseagtsgevlvwpbshxfwbjijtmslkufgofretehjgpcdedstydokejsnrccnkbruawgjmemfqhwmhjsykrejmmexgrsdlwtaybtnhfcapsylopkthboqkvicgcjkyxxubpbqcycioryppydvmwubupxrjlwrwujsiimvpbgkdugjbpqtodgbzzpsduewwovwlfrarfiuaztmmohagkjzzdcnjytamlzpwpfmhlgsdlwfbluxqllcjxbltbrlhgngvtxyksllhfhhzknesqggfazixcotpwwbjenbglhcbnhgjgyimfvfbcezatumthzrqtvdyirxulfhwylbdhkibmiagdgeerriszbnfxmoxgabaxkgkydrnrrbatjbavwdxjqirqivqweqdxeiiotbfidiemakmzbwszgrgekrlalsmbplumxeqmfrulddmbactyuhdljlhhjvxumpkyyzouybtwxtoyiffrderzmztkcdsbhcij"
val xy = (x zip y).filter{ case (a,b) => (a==b) }.map{case (a,b) => a}.mkString
我希望xy将是
pizseagtsgevlvwpbshxfwbjijtmslkufgofretehjgpcdedstydokejsnrccnkbruawgjmemfqhwmhjsykrejmmexgrsdlwtaybtnhfcapsylopkthboqkvicg
但它是
pizseagtsgevlvwpbshxfwbjijtmslkufgofretehjgpcdedstydokejsnrccnkbruawgjmemfqhwmhjsykrejmmexgrsdlwtaybtnhfcapsylopkthboqkvicgydwrsjzpdlblr
不知何故,过滤不能按预期工作。我错过了什么?
答案 0 :(得分:9)
filter
在第一个false
之后不会停止,但会继续遍历剩余的集合。这些附加字符稍后出现在同一位置的两个字符串中。你想要的不是过滤器takeWhile
:
val xy = (x zip y).takeWhile{ case (a,b) => (a==b) }.map{case (a,b) => a}.mkString