recursion - How to define recursive list type in Scala? -


i want create flatten function, take list of various depth , transform flat list.

for example, integers can take list(1, list(2, 3)) , return list(1, 2, 3).

how declare function correctly?

def flatten(list: list[???]): list[t]

looks have use any because depth of list unknown.

def flatten(input: list[any]): list[any] =     input match {       case nil => nil       case head :: tail =>         head match {           case list: list[_] => flatten(list) ::: flatten(tail)           case elem => elem :: flatten(tail)         }     }  scala> flatten(list(1, list(2, 3))) res0: list[any] = list(1, 2, 3) 

if want see couple implementation options check here, , tests here.


Comments

Popular posts from this blog

symfony - InvalidConfigurationException in SecurityExtension.php line 429: No authentication listener registered for firewall "secured_area" -

angular ui router - 10 digest iterations reached in angularjs when using $state.go -

javascript - Handling constructor related functions while testing with mocha and sinon -