Scala recursion function that removes number from list needs work -
i have recursive method in remove should zeroes given list.
def removez(list:list[int], n:int):list[int] = list match { case nil => nil case h::t=> if (h == n) t else h :: removez(t,n) }
this removes 1 0 list if list has multiple zeros won't. tried adding if else statement didn't work such as:
if else(t==n) removez(t,n)
how can have zeroes removed?
that's because after first 0 return tail, have keep iterating:
scala> def removez(list: list[int], n: int): list[int] = list match { | case nil => nil | case h :: t => | if (h == n) | removez(t, n) // 0 found, skip , iterate tail | else | h :: removez(t, n) | } removez: (list: list[int], n: int)list[int] scala> removez(list(1,0,2,0,3), 0) res0: list[int] = list(1, 2, 3)
Comments
Post a Comment