Guest User

Untitled

a guest
Sep 22nd, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. import Foundation
  2.  
  3. enum List<Element> {
  4. case end
  5. indirect case node(Element, next: List<Element>)
  6. }
  7.  
  8. extension List {
  9. func cons(_ x: Element) -> List {
  10. return .node(x, next: self)
  11. }
  12. }
  13.  
  14. extension List: ExpressibleByArrayLiteral {
  15. init(arrayLiteral elements: Element...) {
  16. self = elements.reversed().reduce(.end) { (partialList, element) in
  17. return partialList.cons(element)
  18. }
  19. }
  20. }
  21.  
  22. extension List {
  23. mutating func push(_ x: Element) {
  24. self = self.cons(x)
  25. }
  26.  
  27. mutating func pop() -> Element? {
  28. switch self {
  29. case .end:
  30. return nil
  31. case .node(let x, next: let next):
  32. self = next
  33. return x
  34. }
  35. }
  36. }
  37.  
  38. extension List: IteratorProtocol, Sequence {
  39. mutating func next() -> Element? {
  40. return pop()
  41. }
  42. }
  43.  
  44. extension List: CustomStringConvertible where Element: CustomStringConvertible {
  45. var description: String {
  46. return "[" + self.map { String(describing: $0) }.joined(separator: " -> ") + "]"
  47. }
  48. }
  49.  
  50. let empty = List<String>.end
  51. let list = List.node(1, next: .end)
  52. let secondList = List.end.cons(1).cons(2).cons(3)
  53. var thirdList: List = [0, 1, 2, 3]
  54. thirdList.push(10)
  55. thirdList.pop()
  56.  
  57.  
  58. var stringsList: List = ["a", "b", "c"]
  59. stringsList.push("abc")
Add Comment
Please, Sign In to add comment