Created
December 24, 2014 20:12
-
-
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.
This file contains hidden or 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
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