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

mysql - FireDac error 314 - but DLLs are in program directory -

git - How to list all releases of public repository with GitHub API V3 -

c++ - Getting C2512 "no default constructor" for `ClassA` error on the first parentheses of constructor for `ClassB`? -