Created
January 22, 2019 21:49
-
-
Save nepeckman/633861bb8736f25a2e7d1fe00de13cf1 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 sugar, typetraits | |
type | |
Reducer[T, C] = proc (it: T, coll: C): C {. closure .} | |
Transducer[T1, C1, T2, C2] = proc (reducer: Reducer[T1, C1]): Reducer[T2, C2] {. closure .} | |
proc conj[T](it: T, s: seq[T]): seq[T] = | |
result.deepCopy(s) | |
result.add(it) | |
proc reduce[T, C](s: openArray[T], c: C, op: Reducer[T, C] ): C = | |
result = c | |
for i in s: | |
result = op(i, result) | |
proc map[T1, T2](C: typedesc, op: proc (it: T1): T2): Transducer[T2, C, T1, C] = | |
result = proc (reducer: Reducer[T2, C]): Reducer[T1, C] = | |
result = proc (it: T1, coll: C): C = reducer(op(it), coll) | |
proc filter[T](C: typedesc, op: proc (it: T): bool): Transducer[T, C, T, C] = | |
result = proc (reduce: Reducer[T, C]): Reducer[T, C] = | |
result = proc (it: T, coll: C): C = | |
if op(it): reduce(it, coll) else: coll | |
proc main() = | |
var s = @[1, 2, 3] | |
echo reduce(s, newSeq[string](), | |
filter(seq[string], proc (it: int): bool = it != 2)( | |
map(seq[string], proc (it: int): string = $it)(conj) | |
) | |
) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment