递归方法的逻辑 [英] Logic on a recursive method
问题描述
我的一项练习要求我编写一个递归方法,在该方法中给出一个列表,并且该方法返回仅包含所有其他元素的相同列表.
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.
例如:列表{"a","b","c"}将返回 列表{"a","c"}
for example : List {"a", "b", "c"} would return List{"a","c"}
我正在用Scala编写程序,我知道它已内置在库中,但我不应该使用它们.我只能使用if/else,辅助方法和模式.
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.
推荐答案
使用模式匹配,您还可以以与n::rest
构造相同的方式来解构其前两个元素上的列表.请记住,还要考虑长度不均匀的列表.
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.
这篇关于递归方法的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!