Friday, 12 June 2009

Functions inside functions

Methods inside methods can reference the variables in the outer methods. Check this:
Note the 'n's:

def drop[T](N: Int, l: List[T]): List[T] = {
def dropR(c: Int, curList: List[T]): List[T] = (c, curList) match {
case (_, Nil) => Nil
case (1, _ :: tail) => dropR(N, tail)
case (_, e :: tail) => e :: dropR(c - 1, tail)
dropR(N, l)

The above is a Method to remove every 'N'th element in the list.
Note the way they stick the counter on to the head of the list in the case statement.

This is how I did it - a completely different solution. [Is this Java-ery or funky and functional - I'm not sure].

list.zipWithIndex.partition( a => a._2 % count == count-1 ) a => a._1)

No comments:

Post a comment