Created
May 13, 2016 10:16
-
-
Save xplorld/6c2897882060651ae713433569d3bb6a to your computer and use it in GitHub Desktop.
(Pesudo-)Natural Language Predicates.
This file contains hidden or 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
extension LazySequenceType { | |
public func reduceWhile<T>( | |
initial: T, | |
@noescape combine: (T, Self.Generator.Element) -> T, | |
@noescape criteria: (T) -> Bool | |
)-> T { | |
var generator = self.generate() | |
var now = initial | |
while criteria(now) { | |
guard let next = generator.next() else {return now} | |
now = combine(now,next) | |
} | |
return now | |
} | |
} | |
enum That { | |
case All | |
case Any | |
case MoreThan(Int) | |
case LessThan(Int) | |
func ItemsIn<S:SequenceType,T where S.Generator.Element == T> | |
(arr:S,are predicate:(T -> Bool)) -> Bool { | |
let lazyResults = arr.lazy.map {predicate($0)} | |
switch self { | |
case .All: | |
return !lazyResults.contains(false) | |
case .Any: | |
return lazyResults.contains(true) | |
case .MoreThan(let count): | |
return lazyResults.map{ $0 ? 1 : 0 } | |
.reduceWhile(0, combine: +, criteria: {$0 <= count}) > count | |
case .LessThan(let count): | |
return lazyResults.map{ $0 ? 1 : 0 } | |
.reduceWhile(0, combine: +, criteria: {$0 < count}) < count | |
} | |
} | |
} | |
let numbers = [1,3,2,5,6,7,8,9] | |
let odd:(Int -> Bool) = {$0 % 2 == 1} | |
if (That.MoreThan(2).ItemsIn(numbers,are: odd)) { | |
//yes! | |
print("great!") | |
} | |
print(That.All.ItemsIn([1,3,2,5,6,7,8,9]) {$0 == 5}) | |
print(That.Any.ItemsIn([1,3,2,5,6,7,8,9]) {$0 == 5}) | |
print(That.MoreThan(2).ItemsIn([1,1,2,0,4,5,6,7,8,9]) {return $0 < 3}) | |
print(That.LessThan(2).ItemsIn([1,1,2,0,4,5,6,7,8,9]) {return $0 < 3}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment