Skip to content

Instantly share code, notes, and snippets.

@nahive
Last active January 22, 2017 18:39
Show Gist options
  • Save nahive/218b4113fb2df04555e69c3d26f6896a to your computer and use it in GitHub Desktop.
Save nahive/218b4113fb2df04555e69c3d26f6896a to your computer and use it in GitHub Desktop.
Linked Lists in Swift using custom operator
// maybe someone will find this useful
// i was going through codewars and
// encountered linkedlist challenge
// i noticed special A -> B operator
// and i decided to recreate it it swift :)
//MARK: custom class that holds data
class Node<T> {
var data: T
var next: Node<T>?
init(data: T, next: Node<T>? = nil){
self.data = data
self.next = next
}
var length: Int {
return 1 + (next?.length ?? 0)
}
}
//MARK: equatable protocol
extension Node where T: Equatable {
func occurences(of: T) -> Int {
return (data == of ? 1 : 0) + (next?.occurences(of: of) ?? 0)
}
}
//MARK: operator
precedencegroup LinkedListOp { associativity: right }
infix operator ~> : LinkedListOp
func ~> <T>(l: T, r: Node<T>) -> Node<T> {
return Node(data: l, next: r)
}
func ~> <T>(l: T, r: T) -> Node<T> {
return l ~> Node(data: r)
}
// MARK: how to use
let intLinkedList = 1 ~> 2 ~> 1
let strLinkedList = "a" ~> "b" ~> "c" ~> "d" ~> "b" ~> "b"
intLinkedList.length // 3
strLinkedList.length // 6
intLinkedList.occurences(of: 1) // 2
strLinkedList.occurences(of: "b") // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment