четверг, 15 октября 2009 г.

Kiddy task on Fan

I think that the expressive power of programming language can be easily felt on very simple programs. For example, on one of programming forums someone asked for advice how to convert strings in format "(N[-M],)*" where N and M are integers to list of ints (exactly what you see in any print dialog in print pages text field, something like 5-10,8,13,17).
I wonder that there are people who ask such things on forums, but anyway, let's see the solution of this kiddy task on Fan:

result := Int[,]
"5-10,8, 13"
.split(',', true).each |s|

{
r := s.split('-').map {it.toInt}
result.addAll((r.first..r.last).toList)
}
echo(result.unique.sort)



So, what is going on here?
First, we declare result as an empty list of integers.
Then we take an input string and say that we want to split it by ',' character and remove trailing whitespaces for each string
Then, for each string we do the following:
Split string by '-' char and convert resulting Strig list to list of Integers.
(r.first..r.last) is a literal for range type.
What's interesting here is that inner part produces correct result whether it processes string N-M or just N. Because when there is no '-', split method returns list with one element. And in this case r.first == r.last and we get range with only one int.

And, finally, print the result with removing duplicates and sorting

Комментариев нет:

Отправить комментарий