Skip to content

Instantly share code, notes, and snippets.

@gregorydickson
Last active May 12, 2016 17:11
Show Gist options
  • Save gregorydickson/746210d8ed5247b7a6134c2e61b2fce5 to your computer and use it in GitHub Desktop.
Save gregorydickson/746210d8ed5247b7a6134c2e61b2fce5 to your computer and use it in GitHub Desktop.
import java.util.ArrayList
def flatten
flatten = { list ->
switch(list){
case list.size() == 0:
return
break
case {list.head() instanceof Integer && list.size() == 1}:
result = list
break
case {list.head() instanceof Integer && list.size() == 2}:
result = [list.head()] + flatten(list.tail())
break
case {list.head() instanceof ArrayList && list.size() > 1}:
result = flatten(list.head()) + flatten(list.tail())
break
case {list.head() instanceof ArrayList && list.size() == 1}:
result = flatten(list.head())
break
case {list.head() instanceof Integer && list.size() > 1}:
result = [list.head()] + flatten(list.tail())
break
case {list.head() instanceof Integer && list.size() == 1}:
result = [list.head()]
break
}
}.trampoline()
def newList = flatten( [[1], 2, [[3, 4], 5]])
assert newList == [1, 2, 3, 4, 5]
println(newList)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment