Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the Stream Sieve benchmark #427

Open
hugomg opened this issue Jul 24, 2021 · 0 comments · May be fixed by #466
Open

Add the Stream Sieve benchmark #427

hugomg opened this issue Jul 24, 2021 · 0 comments · May be fixed by #466

Comments

@hugomg
Copy link
Member

hugomg commented Jul 24, 2021

Some gradual typing papers use the following benchmark with the naive prime sieve using lazy streams. Now that we have closures in Pallene, it might be interesting to add it to the benchmark list

I don't remember why the stream_take function is there. Maybe I added it for debugging?

-- Simple streams library for building infinite lists.
-- A stream is a cons of a value and a thunk that computes the next value
-- when applied.

-- (any, any->any) -> any
local function make_stream(v, f)
    return {v=v, f=f}
end

local function stream_head(st)
    return st.v
end

local function stream_tail(st)
    return st.f(st.v)
end

local function stream_get(st, n)
    for _ = 1, n-1 do
        st = stream_tail(st)
    end
    return stream_head(st)
end

local function stream_take(st, n)
    local elems = {}
    for i = 1, n do
        elems[i] = stream_head(st)
        st = stream_tail(st)
    end
    return elems
end

----------------------------------------------

-- Build a stream of integers starting from 1
local function count_from(n)
    return make_stream(n, function(i) return count_from(i+1) end)
end

-- Filter all multiples of n
local function sift(n, st)
    local hd = stream_head(st)
    local tl = stream_tail(st)
    if hd % n == 0 then
        return sift(n, tl)
    else
        return make_stream(hd, function() return sift(n, tl) end)
    end
end

-- Naive sieve of Erasthostenes
local function sieve(st)
    local hd = stream_head(st)
    local tl = stream_tail(st)
    return make_stream(hd, function() return sieve(sift(hd, tl)) end)
end

--
local prime_stream = sieve(count_from(2))

local function get_prime(n)
    return stream_get(prime_stream, n)
end

return {
    get_prime = get_prime
}
hugomg added a commit that referenced this issue Aug 18, 2021
@hugomg hugomg linked a pull request Aug 18, 2021 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant