Created
May 9, 2018 06:55
-
-
Save Tony-Y/00a21399503ef9947d79ca8df842f679 to your computer and use it in GitHub Desktop.
Swift Operators for Python.slice
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
import Python | |
// Slice Operators | |
precedencegroup SliceFormationPrecedence { | |
associativity: left | |
lowerThan: AdditionPrecedence | |
} | |
infix operator .~: SliceFormationPrecedence | |
prefix operator .~ | |
postfix operator .~ | |
infix operator .|: SliceFormationPrecedence | |
prefix operator .| | |
func .~ (lhs: Int, rhs: Int) -> Python.PyValue { | |
return Python.slice.call(with: lhs, rhs, 1) | |
} | |
prefix func .~ (rhs: Int) -> Python.PyValue { | |
return Python.slice.call(with: Python.None, rhs, 1) | |
} | |
postfix func .~ (lhs: Int) -> Python.PyValue { | |
return Python.slice.call(with: lhs, Python.None, 1) | |
} | |
func .| (lhs: Python.PyValue, rhs: Int) -> Python.PyValue { | |
return Python.slice.call(with: lhs.start, lhs.stop, rhs) | |
} | |
prefix func .| (rhs: Int) -> Python.PyValue { | |
return Python.slice.call(with: Python.None, Python.None, rhs) | |
} | |
// NumPy Example | |
/* | |
let np = Python.import("numpy") | |
let a = np.arange.call(with: 10) | |
let view1 = a[0.~ .| 2] // or a[.|2] | |
print(view1) // [0 2 4 6 8] | |
let view2 = a[.~8 .| 2] | |
print(view2) // [0 2 4 6] | |
let view3 = a[(-2).~1 .| -1] | |
print(view3) // [8 7 6 5 4 3 2] | |
a[.|2] = np.arange.call(with: 10, 15) | |
print(a) // [10 1 11 3 12 5 13 7 14 9] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment