Skip to content

Instantly share code, notes, and snippets.

@DeepSky8
Created July 2, 2014 17:57
Show Gist options
  • Select an option

  • Save DeepSky8/1ec085a35eab0160cfdb to your computer and use it in GitHub Desktop.

Select an option

Save DeepSky8/1ec085a35eab0160cfdb to your computer and use it in GitHub Desktop.
P20 (*) Remove the Kth element from a list. Return the list and the removed element in a Tuple. Elements are numbered from 0. Example: scala> removeAt(1, List('a, 'b, 'c, 'd)) res0: (List[Symbol], Symbol) = (List('a, 'c, 'd),'b)
def removeAt[A](n: Int, input: List[A]): (List[A], A) = {
def removeAtHelper(input: List[A], p: Int = n): List[A] = input match{
case Nil => Nil
case h :: t => if(p > 0) h :: removeAtHelper(t, p - 1) else t
}
def symbol(input: List[A], q: Int): Option[A] = input match {
case Nil => Nothing
case h :: t => if(q > 0) symbol(t, q - 1) else t.headOption.getOrElse(Nothing)
}
(removeAtHelper(input), symbol(input))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment