Showing posts with label list. Show all posts
Showing posts with label list. Show all posts

Sunday, 14 June 2009

String parsing thru lists

Filter numbers from strings.

println( "there are 7 numbers 8 in 2 here"
.toList.filter(Character.isDigit) )


Load the first word only.

println(("first word only".toList.takeWhile(c => c != ' ') ).mkString)

Funky stuff with for loops & prepopulating lists

You can pre populate a list with a loop like "val list = 1 to 20"

You can return stuff from a for loop with the "yield" command

def looping() = {
val myList = (1 to 20 by 3)
println(myList)

val list2 = for( i <- myList if i % 2 == 0 ) yield i
println(list2)
}

cool list functions

list functions:

list.zipWithIndex = (a,b,c) => (a=>1,b=>2,c=>3)
list.slice(start,end) = cuts out this part of the list
list.take(n) ::: list.drop(n) == list = get the first n elements append them to not the first n elements

Friday, 1 May 2009

Scala - Flatten lists & use asInstanceOf

 
def flatten3(l: List[_]): List[_] = {
l.flatMap(a => {
if (a.isInstanceOf[List[_]]) flatten3(a.asInstanceOf[List[_]])
else List(a)
})
}