Skip to content

Instantly share code, notes, and snippets.

@jarsen
Created December 24, 2014 20:12
Show Gist options
  • Save jarsen/68e3e4ae9643f6886712 to your computer and use it in GitHub Desktop.
Save jarsen/68e3e4ae9643f6886712 to your computer and use it in GitHub Desktop.
Functional linked list implemented in Swift. Inspired by functional data structure chapter in Functional Programming in Swift, and had to look at Swiftz to figure out it needed the @autoclosure... haven't quite figured out why but otherwise it seems to get into an infinite loop.
enum List<T> : Printable {
case Empty
case Node(@autoclosure() -> T, Box<List<T>>)
init(_ head: T, _ tail: Box<List<T>>) {
self = .Node(head, tail)
}
var description: String {
get {
switch self {
case Empty:
return "[]"
case let .Node(head, tailBox):
return "\(head()) \(tailBox.unbox.description)"
}
}
}
}
func head<T>(list: List<T>) -> T? {
switch list {
case .Empty:
return nil
case let .Node(head, _):
return head()
}
}
func tail<T>(list: List<T>) -> List<T> {
switch list {
case .Empty:
return List.Empty
case let .Node(_, tailBox):
return tailBox.unbox
}
}
infix operator => {
associativity right
precedence 150
}
func => <T>(lhs: T, rhs: List<T>) -> List<T> {
return List.Node(lhs, Box(rhs))
}
let foo = 1 => 2 => 3 => List.Empty
println(foo.description)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment