Created
September 25, 2016 07:08
-
-
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)
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
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