以下Scala代码有什么问题?

时间:2015-12-11 15:30:35

标签: scala filtering

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

不知何故,过滤不能按预期工作。我错过了什么?

1 个答案:

答案 0 :(得分:9)

filter在第一个false之后不会停止,但会继续遍历剩余的集合。这些附加字符稍后出现在同一位置的两个字符串中。你想要的不是过滤器takeWhile

val xy = (x zip y).takeWhile{ case (a,b) => (a==b) }.map{case (a,b) => a}.mkString