Logic on a recursive method

时光毁灭记忆、已成空白 提交于 2020-01-06 19:35:35

问题


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.



来源:https://stackoverflow.com/questions/35021213/logic-on-a-recursive-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!