Skip to content

Instantly share code, notes, and snippets.

View oisdk's full-sized avatar

Donnacha Oisín Kidney oisdk

View GitHub Profile
extension CollectionType {
subscript(i1: Index, i2: Index, rest: Index...) -> PermutationGenerator<Self, [Self.Index]> {
get {
return PermutationGenerator(elements: self, indices: [i1, i2] + rest)
}
}
}
extension Array {
subscript(i1: Index, i2: Index, rest: Index...) -> [T] {
import Foundation
func randomNumber<S : SequenceType where S.Generator.Element == Double>
(probabilities: S) -> Int {
var sum = 0.0
let accum = probabilities.map {
prob -> Double in
sum += prob
return sum
}
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]} ?? [])} ?? []
public struct StridingSliceView<C : CollectionType where C.Index : Strideable> : SequenceType {
private let col: C
private let str: StrideTo<C.Index>
public func generate() -> PermutationGenerator<C, StrideTo<C.Index>> {
return PermutationGenerator(elements: col, indices: str)
}
}
public struct MatrixIndex: BidirectionalIndexType {
public let x, y : Int
private let columns: Int
public func successor() -> MatrixIndex {
return (x + 1 == columns) ?
MatrixIndex(x: 0, y: y + 1, columns: columns) :
MatrixIndex(x: x + 1, y: y, columns: columns)
// Equivalent to foldM
extension Sliceable where
SubSlice : Sliceable,
SubSlice.Generator.Element == Generator.Element,
SubSlice.SubSlice == SubSlice {
func flatReduce
<U, S : SequenceType where S.Generator.Element == U>
(initial: U, @noescape combine: (U, Generator.Element) -> S) -> [U] {
return first.map {
postfix operator < {}
postfix operator <= {}
prefix operator > {}
prefix operator >= {}
postfix func < <C : Comparable>(lhs: C)(_ rhs: C) -> Bool {
return lhs < rhs
}
postfix func <= <C : Comparable>(lhs: C)(_ rhs: C) -> Bool {
return lhs <= rhs
}
extension Sliceable {
public func uncons() -> (Generator.Element, SubSlice)? {
return first.map { ($0, dropFirst(self)) }
}
public func uncons() -> (
Generator.Element,
Generator.Element,
SubSlice)? {
var i = startIndex
struct _Empty<T>: ArrayLiteralConvertible {
init(arrayLiteral: T...) {
assert(arrayLiteral.isEmpty)
}
}
func ~= <C : CollectionType>(lhs: _Empty<C.Generator.Element>, rhs: C) -> Bool {
return rhs.isEmpty
}
public protocol VectorType {
typealias Scalar
var endIndex: Int {get}
subscript(_: Int) -> Scalar {get set}
init()
}
public struct EmptyVector<T> : VectorType {
public init() {}
typealias Scalar = T