Ideas about filtering


#1

n/a


#2

There is a filter method on iterators. For example to get only odd numbers in a list:

val it = Iterator(1, 2, 4, 3, 7, 8)
val it1 = it.filter(_ % 2 == 1)
it1.foreach(println) 
// 1
// 3
// 7

regards,
Siddhartha


#3

I’m not sure what you mean by punctuation?
You want only some of the chars (like only digits and letters)?

you can use Iterator.filter or Iterator.filterNot
and predicates on Char: isDigit, isControl, isLetter, isLetterOrDigit, and so on…


#4

“Andy Jones”, you can use piazza and I have office hours too… :wink:


#5

Expanding on the above: as you’re getting used to the idea of higher-order functions, I recommend doing a lot of playing with .filter() (filter out some of the elements) and .map() (transform each element into something else), which in my experience tend to be the most commonly-useful ones.

There are a bajillion little ways to use these, most of them little one-liners like this – the surprising bit is often how concise the results are. For example, depending on how you define it, the answer to your question might be as simple as it.filter(_.isLetterOrDigit). (As shown here.)

More questions welcomed…