Skip to content

Instantly share code, notes, and snippets.

@seoh
Last active August 29, 2015 14:03
Show Gist options
  • Save seoh/06dd446a4e6342d69a09 to your computer and use it in GitHub Desktop.
Save seoh/06dd446a4e6342d69a09 to your computer and use it in GitHub Desktop.
Butcher protocol for head/tail of Array

butcher.swift

head/tail implementation using protocol

butcher.python.swift

another implementation inspired from python

// Swift // python
var arr = [1,2,3] // arr = [1,2,3]
arr[1..(-1)] // arr[1:-1]
arr[1..(-2)] // arr[1:-2]
@infix func .. (lhs: Int, rhs: Int) -> (Int, Int) {
return (lhs, rhs)
}
extension Array {
subscript(range: (Int, Int)) -> [T] {
var (start, end) = range
end = end < 0 ? self.count + end : end
return Array(self[start...end])
}
var head: T {
get { return self[0] }
}
var tail: [T] {
get { return self[1..(-1)] }
}
}
protocol Butcher {
typealias T
var head: T { get }
var tail: Array<T> { get }
}
extension Array:Butcher {
typealias Foo = T
var head: T {
// non-optional for optimization
get { return self[0] }
}
var tail: Array<T> {
get {
return self.count > 1 ? Array(self[1..<self.count]) : []
}
}
}
var char = ["a", "b", "c", "d"]
println(char.head)
println(char.tail)
var arr = [1]
println(arr.head)
println(arr.tail)
var arr2:Array<Int> = []
arr2.head // error occured
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment