[Swift]順列
2015/05/10
swift
順列
swiftです。仕組みがいまいちよくわかってないですが、とりあえずメモ
ほんと、魔術というか、仕組みがわかってないので、たんなる写経となってしまっています。
decomposeは分解とかそういう意味らしい。
まさしく、functional programmingという感じ。
コード
ほんと、魔術というか、仕組みがわかってないので、たんなる写経となってしまっています。
decomposeは分解とかそういう意味らしい。
まさしく、functional programmingという感じ。
コード
extension Array {
var decompose : (head: T, tail: [T])? {
return (count > 0) ? (self[0], Array(self[1..<count])) : nil
}
}
infix operator >>= {}
func >>=<A, B>(xs: [A], f: A -> [B]) -> [B] {
return xs.map(f).reduce([], combine: +)
}
func between<T>(x: T, ys: [T]) -> [[T]] {
if let (head, tail) = ys.decompose {
return [[x] + ys] + between(x, tail).map { [head] + $0 }
} else {
return [[x]]
}
}
func permutations<T>(xs: [T]) -> [[T]] {
if let (head, tail) = xs.decompose {
return permutations(tail) >>= { permTail in
between(head, permTail)
}
} else {
return [[]]
}
}
let a = permutations([0, 1, 2, 3])
println("\(a)")
: