Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

functional programming - Scala - Two Lists to Tuple List

Last year I had quite a bit of experience with standard ML, but I haven't done any real functional programming in about 10 months. Now that I'm on the Scala bandwagon, I'm having trouble finding an operation which I used extensively in standard ML when writing a compiler (although to be fair, this method may not have been a library method).

Basically, I have two lists:

List("a","b","c")
List(1,2,3)

And I want an operation that will give me a list of tuples like this:

List(("a",1), ("b",2), ("c",3))

Is there a standard Scala function I can use to get this result? (I think we called it a zip function in standard ML, but that seems to refer to something different when I was searching for Scala zip functions.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're right you can use zip:

val a = List("a","b","c")
// a: List[String] = List(a, b, c)

val b = List(1,2,3)
// b: List[Int] = List(1, 2, 3)

a zip b  // beautified a.zip(b) 
//res0: List[(String, Int)] = List((a,1), (b,2), (c,3))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...