Quick actions

cmd+k|ctrl+k

Navigation

Languages

stream api 

Snippet info

Language

Ruby

Visibility

public

Author

yoneda

Created

2018-09-27T13:33:38Z

Updated

2018-09-27T13:40:13Z

def repeat(n, fn = ->x{x})
    [n, ->{repeat(fn.call(n), fn)}]
end

def map(mapper, stream)
    [mapper.call(stream.first), stream.last.nil? ? nil : ->{map(mapper, stream.last.call)}]
end

def take(n, stream)
    [stream.first, n == 1 ? nil : ->{take(n - 1, stream.last.call)}]
end

def drop(n, stream)
    if n.zero?
        stream
    else
        drop(n - 1, stream.last.call)
    end
end

def realize(n, stream)
    if n.zero?
        []
    else
        [stream.first] + if stream.last.nil?
            []
        else
            realize(n - 1, stream.last.call)
        end
    end
end

p realize(20, map(->x{Rational(1, x)}, take(10, drop(1000, repeat(1, ->x{x + 1})))))
INFO