开发者

Scala - how to get a list element

I'm trying to get element from a list:

data =List(("2001",13.1),("2009",3.1),("2004",24.0),("2011",1.11))

Any help? Task 开发者_如何学Gois to print separatly Strings and numbers like:

print(x._1+" "+x._2) 

but this is not working.


One good practice with functional programming is to do as much as possible with side-effect-free transformations of immutable objects.

What that means (in this case) is that you can convert the list of tuples to a list of strings, then limit your side-effect (the println) to a single step at the very end.

val data = List(("2001",13.1),("2009",3.1),("2004",24.0),("2011",1.11))
val lines = data map { case(a,b) => a + " " + b.toString }
println(lines mkString "\n") 


scala> val data =List(("2001",13.1),("2009",3.1),("2004",24.0),("2011",1.11))
data: List[(java.lang.String, Double)] = List((2001,13.1), (2009,3.1), (2004,24.0), (2011,1.11))

scala> data.foreach(x => println(x._1+" "+x._2))
2001 13.1
2009 3.1
2004 24.0
2011 1.11


val list = List(("2001",13.1),("2009",3.1),("2004",24.0),("2011",1.11))
println(list map (_.productIterator mkString " ") mkString "\n")

2001 13.1
2009 3.1
2004 24.0
2011 1.11


I would use pattern matching which yields a programming pattern that scales better for larger tuples and more complex elements:

data.foreach { case (b,c) => println(b + " " + c) }


for the Strings, use

List((1,"aoeu")).foreach(((_:Tuple2[String,_])._1) andThen print)
for the numbers, use
List(("aoeu",13.0)).foreach(((_:Tuple2[_,Double])._2) andThen print)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜