Senin, 10 Januari 2011

List Scala

$ cat list-test.scala
val aList = List(1,2,3)
println( aList )
println()

val bList = List(4,5,6)
val newList = aList :: bList
println( newList )
println()

val yaNewList = aList ::: bList
println( yaNewList )
println( "The first one is " + yaNewList(0) )
println( "The last one is " + yaNewList(yaNewList.length -1) )
println(
"# of elements that are greater than 2: "
+ yaNewList.count( e => e > 2 )
)
println(
"The list that the leading two elements are eliminated: "
+ yaNewList.drop( 2 )
)
println(
"The list that the trailing three elements are eliminated: "
+ yaNewList.dropRight( 3 )
)
println(
"Whether or not the value 4 exists: "
+ yaNewList.exists( e => e == 4 )
)
println(
"Filtering data in a specific condition: "
+ yaNewList.filter( e => e < 4 ) ) println( "Checking if all the elements are positive: " + yaNewList.forall( e => e > 0 )
)
println(
"Processing all the elements by a particular logic: "
+ yaNewList.map( e => e * 10 )
)
println(
"Creating a new string from the list: "
+ yaNewList.mkString( ", " )
)
println(
"Sorting with some logic: "
+ yaNewList.sort( (s,t) => s > t )
)
println(
"Removing elements by a specified rule: "
+ yaNewList.remove( e => e % 2 == 0 )
)
println( "Head: " + yaNewList.head )
println( "Tail: " + yaNewList.tail )
println( "Last: " + yaNewList.last )

println()

$ scala list-test.scala
List(1, 2, 3)

List(List(1, 2, 3), 4, 5, 6)

List(1, 2, 3, 4, 5, 6)
The first one is 1
The last one is 6
# of elements that are greater than 2: 4
The list that the leading two elements are eliminated: List(3, 4, 5, 6)
The list that the trailing three elements are eliminated: List(1, 2, 3)
Whether or not the value 4 exists: true
Filtering data in a specific condition: List(1, 2, 3)
Checking if all the elements are positive: true
Processing all the elements by a particular logic: List(10, 20, 30, 40, 50, 60)
Creating a new string from the list: 1, 2, 3, 4, 5, 6
Sorting with some logic: List(6, 5, 4, 3, 2, 1)
Removing elements by a specified rule: List(1, 3, 5)
Head: 1
Tail: List(2, 3, 4, 5, 6)
Last: 6

Tidak ada komentar:

Posting Komentar