Logic on a recursive method

2019-09-05 00:23发布

问题:

One of my exercises requires me to write a recursive method in which a list is given, and it returns the same list with only every other element on it.

for example : List {"a", "b", "c"} would return List{"a","c"}

I am writing in scala, and I understand that it has built in library but I am not supposed to use those. I can only use if/else, helper methods,and patterns.

How could I parse thru a list using head and tail only?

so far I have this:

def removeLetter(list:List[String]):List[String]=list match{

 case Nil => Nil
 case n::rest=>  

  if (n == rest){  // I understand that this doesn't quite work.
     tail
   }
  else
     head::removeLetter(tail)
  }
   }

I am looking for the logic and not code.

回答1:

Using pattern matching, you can also deconstruct a list on it's first two elements in the same way you're doing with your n::rest construction. Just remember to also take lists with uneven length into account.



回答2:

  • You correctly stated one base-case to the recursion: In case of an empty list, the result is again the empty list. case Nil => Nil
  • There is a second base-case: A list containing a single element is again the list itself. case x :: Nil => x :: Nil
  • You can formulate the recursive step as follows: Given a list with at least two elements, the result is a list containing the first element, followed by every other element of the list after the second element. case x :: y :: z => x :: removeLetter(z) (Note that here, x and y are both of type String while z is of type List[String])

Remark: If you wanted to, you could also combine both base-cases, as in both cases, the input to the function is its output.