Skip to content

Instantly share code, notes, and snippets.

@tel
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tel/ee75f5c3ee4fc818d74d to your computer and use it in GitHub Desktop.
Save tel/ee75f5c3ee4fc818d74d to your computer and use it in GitHub Desktop.
Left-view enumerations of Swift Strings
protocol Viewl {
typealias El
func uncons() -> (El, Self)?
}
func head<X:Viewl>(x: X) -> X.El? { return x.uncons()?.0 }
func tail<X:Viewl>(x: X) -> X? { return x.uncons()?.1 }
extension String:Viewl {
typealias El = Character
func uncons() -> (Character, String)? {
return isEmpty ? nil : (self[startIndex], dropFirst(self))
}
}
extension Array:Viewl {
typealias El = Element
func uncons() -> (Array.Element, Array)? {
return isEmpty ? nil : (self[0], Array(dropFirst(self)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment