Skip to content

Instantly share code, notes, and snippets.

@Tony-Y
Tony-Y / NumPySlice.swift
Created May 9, 2018 06:55
Swift Operators for Python.slice
import Python
// Slice Operators
precedencegroup SliceFormationPrecedence {
associativity: left
lowerThan: AdditionPrecedence
}
infix operator .~: SliceFormationPrecedence
prefix operator .~
@Tony-Y
Tony-Y / ArraySliceWithStride.swift
Last active July 9, 2018 05:16
ArraySliceWithStride: a[start .~ end .| step]
struct ArraySliceWithStride<Element> {
typealias Base = Array<Element>
private let _base: Base
private let _slice: Array<Any>.Slice
private var _start: Int { return _slice.start! }
let count: Int
private var _stride: Int { return _slice.stride }
init(_ base: Base, from start: Base.Index?, to end: Base.Index?, by stride: Base.Index.Stride) {
self._base = base
@Tony-Y
Tony-Y / StrideOperator2.swift
Last active April 25, 2018 14:26
Swift Stride Operators: (a..<b)%%step and (a...b)%%step
struct StrideIterator<Element : Strideable> {
var element: Element
let step: Element.Stride
}
extension StrideIterator : IteratorProtocol where Element : Strideable {
mutating func next() -> Element? {
guard step != 0 else { return nil }
defer { element = element.advanced(by: step) }
@Tony-Y
Tony-Y / StrideOperator.swift
Created April 21, 2018 08:56
Swift Stride Operator, e.g. (0..<10)/2 and (0...10)/2
// Open Range Stride
func / <T: Strideable>(left: Range<T>, right: T.Stride) -> StrideTo<T> {
return stride(from: left.lowerBound, to: left.upperBound, by: right)
}
// Closed Range Stride
func / <T: Strideable>(left: ClosedRange<T>, right: T.Stride) -> StrideThrough<T> {
return stride(from: left.lowerBound, through: left.upperBound, by: right)
}