Skip to content

Instantly share code, notes, and snippets.

@geekynils
Created October 13, 2017 20:41
Show Gist options
  • Save geekynils/91f76ebc935dc1f95948ac9f45372baf to your computer and use it in GitHub Desktop.
Save geekynils/91f76ebc935dc1f95948ac9f45372baf to your computer and use it in GitHub Desktop.
// Linked list using optionals and enums with associated values.
// See https://medium.com/@andre_videla/total-programming-in-swift-526508c12a74
import Foundation
class Node<Elem> {
init(withElement elem: Elem, attachToList tail: List<Elem>) {
self.elem = elem
self.tail = tail
}
let elem: Elem
private let tail: List<Elem>
}
enum List<Elem> {
case Empty
indirect case Node(Elem, List<Elem>)
}
func count<Elem>(list: List<Elem>) -> Int {
switch list {
case .Empty: return 0
case let .Node(_, rest): return 1 + count(list: rest)
}
}
func print(list: List<Int>) {
switch list {
case .Empty: print()
case let .Node(elem, rest): do {
print("\(elem) ", terminator:"")
print(list:rest)
}
}
}
var myList = List<Int>.Node(1, .Empty)
myList = List<Int>.Node(2, myList)
myList = List<Int>.Node(3, myList)
let numberOfItems = count(list: myList)
print("My list has \(numberOfItems) items!")
print("Here are the items: ", terminator:"")
print(list: myList)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment