Skip to content

Instantly share code, notes, and snippets.

@bhargavg
Created September 25, 2016 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhargavg/f66714a66af83e63a9f7dbd40d3a9245 to your computer and use it in GitHub Desktop.
Save bhargavg/f66714a66af83e63a9f7dbd40d3a9245 to your computer and use it in GitHub Desktop.
Functional Integer List in Swift - Inspired by Programming Languages Lecture by Dan Grossman (Coursera)
indirect enum IntList {
case empty
case cons(Int, IntList)
}
extension IntList {
static func append(_ xs: IntList, _ ys: IntList) -> IntList{
switch xs {
case .empty: return ys;
case let .cons(head, tail): return .cons(head, append(tail, ys));
}
}
func appending(_ xs: IntList) -> IntList {
return IntList.append(self, xs);
}
}
func print(list: IntList) {
func formatter(_ list: IntList) -> String {
switch list {
case .empty:
return ""
case let .cons(head, tail):
let separator: String
if case .empty = tail {
separator = ""
} else {
separator = ", "
}
return String(head) + separator + formatter(tail)
}
}
print("[" + formatter(list) + "]");
}
let xList: IntList = .cons(2, .cons(1, .empty))
let yList: IntList = .cons(4, .cons(5, .empty))
let zList = xList.appending(yList)
print(list: xList);
print(list: yList);
print(list: zList);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment