Advertisement
Guest User

Untitled

a guest
Jul 26th, 2017
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. /*
  2.  
  3. Remove the Kth element from a list.
  4. Return the list and the removed element in a Tuple. Elements are numbered from 0.
  5. Example:
  6. scala> removeAt(1, List('a, 'b, 'c, 'd))
  7. res0: (List[Symbol], Symbol) = (List('a, 'c, 'd),'b)
  8.  
  9. */
  10.  
  11. def removeAt[A](index: Int, list: List[A]): Tuple2[List[A], A] = (index, list) match {
  12. case (0, head :: tail) => (tail, head)
  13. case (_, head :: tail) => {
  14. val (acc, element) = removeAt(index - 1, tail)
  15. (head :: acc, element)
  16. }
  17. }
  18.  
  19. /*
  20.  
  21. Duplicate the elements of a list a given number of times.
  22. Example:
  23. scala> duplicateN(3, List('a, 'b, 'c, 'c, 'd))
  24. res0: List[Symbol] = List('a, 'a, 'a, 'b, 'b, 'b, 'c, 'c, 'c, 'c, 'c, 'c, 'd, 'd, 'd)
  25.  
  26. */
  27.  
  28. def duplicateN[A](times: Int, list: List[A]): List[A] = list.flatMap((e: A) => List.fill(times)(e))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement