Last active
August 29, 2015 14:24
-
-
Save oisdk/d9a8f7b82cedecf001a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func flattenGen<G : GeneratorType, T where G.Element == T?>(var gen: G) -> [T] { | |
return gen.next().map { ($0.map { [$0] } ?? []) + flattenGen(gen) } ?? [] | |
} | |
func flatten<S : SequenceType, T where S.Generator.Element == T?>(seq: S) -> [T] { | |
return flattenGen(seq.generate()) | |
} | |
func flatAr<T>(ar: ArraySlice<T?>) -> ArraySlice<T> { | |
return ar.last.map {flatAr(dropLast(ar)) + ($0.map{[$0]} ?? [])} ?? [] | |
} | |
func squeezle< | |
C : RangeReplaceableCollectionType, T where | |
C.Index : BidirectionalIndexType, | |
C.Generator.Element == T? | |
>(var c: C) -> [T] { | |
return c.isEmpty ? [] : {squeezle(c) + ($0.map {[$0]} ?? [])}(removeLast(&c)) | |
} | |
let jo: [Int?] = [1, 2, nil, 3] | |
flatAr(ArraySlice(jo)) // [1, 2, 3] | |
flatten(jo) // [1, 2, 3] | |
squeezle(jo) // [1, 2, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment