Created
June 16, 2017 08:42
-
-
Save yoxisem544/c1092b4820b2d9e0ea3e2f5331a52d78 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
import UIKit | |
indirect enum LinkedListNode<T> { | |
case value(element: T, next: LinkedListNode<T>) | |
case end | |
} | |
extension LinkedListNode : Sequence { | |
typealias Iterator = LinkedListIterator<T> | |
func makeIterator() -> LinkedListIterator<T> { | |
return LinkedListIterator(current: self) | |
} | |
} | |
struct LinkedListIterator<T> : IteratorProtocol { | |
var current: LinkedListNode<T> | |
mutating func next() -> T? { | |
switch current { | |
case let .value(element: e, next: next): | |
current = next | |
return e | |
case .end: | |
return nil | |
} | |
} | |
} | |
extension LinkedListNode : ExpressibleByArrayLiteral { | |
typealias Element = T | |
init(arrayLiteral elements: Element...) { | |
// construct a linked list from its end. | |
// more efficient. | |
self = elements.reversed().reduce(LinkedListNode.end) { (currentNode, nextValue) -> LinkedListNode<Element> in | |
return LinkedListNode.value(element: nextValue, next: currentNode) | |
} | |
} | |
} | |
let list: LinkedListNode<String> = ["๐","๐","๐","๐","๐"] | |
list.forEach({ print($0) }) | |
list.contains("") | |
let numbers = [1,2,3,4,5,6,7] | |
print(numbers.filter({ $0 > 3 }).count) | |
extension Sequence { | |
func count(_ shouldCount: (Iterator.Element) -> Bool) -> Int { | |
var count = 0 | |
for element in self { | |
if shouldCount(element) { | |
count += 1 | |
} | |
} | |
return count | |
} | |
} | |
print(numbers.count { $0 > 3 }) | |
extension Sequence where Self.SubSequence : Sequence, | |
Self.SubSequence.Iterator.Element == Self.Iterator.Element { | |
func eachPair() -> AnySequence<(Iterator.Element, Iterator.Element)> { | |
return AnySequence(zip(self, self.dropFirst())) | |
} | |
} | |
numbers.eachPair().forEach { print($0) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment