Created
October 13, 2017 20:41
-
-
Save geekynils/91f76ebc935dc1f95948ac9f45372baf to your computer and use it in GitHub Desktop.
This file contains 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
// 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