SHARE
TWEET

Untitled

a guest Jul 17th, 2019 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using Transducers
  2. using Transducers: R_, wrap, Unseen, xform, inner, wrapping, wrap, unwrap
  3. import Transducers: start, next, complete
  4.  
  5. struct TransductionBuffer
  6.     buffer::Vector{Any}
  7. end
  8.  
  9. Base.iterate(itr::TransductionBuffer, ::Any = nothing) =
  10.     if isempty(itr.buffer)
  11.         nothing
  12.     else
  13.         popfirst!(itr.buffer), nothing
  14.     end
  15.  
  16. struct Transduction{T} <: Transducer
  17.     ixf::T
  18. end
  19.  
  20. function start(rf::R_{Transduction}, result)
  21.     buffer = []
  22.     itr = xform(rf).ixf(TransductionBuffer(buffer))
  23.     return wrap(rf, (itr, Unseen(), buffer), start(inner(rf), result))
  24. end
  25.  
  26. next(rf::R_{Transduction}, result, input) =
  27.     wrapping(rf, result) do (itr, itstate0, buffer), result
  28.         push!(buffer, input)
  29.         if itstate0 isa Unseen
  30.             ret = iterate(itr)
  31.         else
  32.             ret = iterate(itr, itstate0)
  33.         end
  34.         while true
  35.             if ret === nothing
  36.                 return (itr, itstate0, buffer), reduced(complete(inner(rf), result))
  37.             end
  38.             itout, itstate = ret
  39.             result = next(inner(rf), result, itout)
  40.             if result isa Reduced || isempty(buffer)
  41.                 return (itr, itstate, buffer), result
  42.             end
  43.             ret = iterate(itr, itstate)
  44.         end
  45.     end
  46.  
  47. complete(rf::R_{Transduction}, result) =
  48.     complete(inner(rf), unwrap(rf, result)[2])
  49.  
  50. @show collect(Transduction(itr -> Base.Generator(x -> x + 1, itr)), 1:2)
  51. @show collect(Transduction(itr -> Iterators.filter(isodd, itr)), 1:2)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top