Skip to content

Instantly share code, notes, and snippets.

@hiroshi-maybe
Created June 14, 2019 21:09
Show Gist options
  • Save hiroshi-maybe/33c700b57eb48b50c104c1e3752c8310 to your computer and use it in GitHub Desktop.
Save hiroshi-maybe/33c700b57eb48b50c104c1e3752c8310 to your computer and use it in GitHub Desktop.
flatten nested integers by Swift
import Foundation
indirect enum Exp {
case num(Int)
case list([Exp])
}
// [1,2,[3,[4,5],6],7,[[8,9]],10]
func flatten(_ e: Exp) -> [Int] {
var res = [Int]()
switch e {
case .num(let n):
res.append(n)
case .list(let es):
for ns in es.map({ flatten($0) }) {
for n in ns { res.append(n) }
}
}
return res
}
let e: Exp = .list([.num(1),.num(2),.list([.num(3),.list([.num(4),.num(5)]),.num(6)]),.num(7),.list([.list([.num(8),.num(9)])]),.num(10)])
print(flatten(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment