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

[feature request] chain from iterable, bind? #36

Open
coldfix opened this issue Mar 30, 2017 · 0 comments
Open

[feature request] chain from iterable, bind? #36

coldfix opened this issue Mar 30, 2017 · 0 comments
Assignees
Labels
Milestone

Comments

@coldfix
Copy link

coldfix commented Mar 30, 2017

Hey,

one composition that seems to be missing is chaining iterators when the list of iterators is given as an iterator - similar to itertools.chain.from_iterable in python.

E.g. something like this:

function chain_from_iterable(iter, gen, state)
  return chain(table.unpack(totable(iter, gen, state))
--return reduce(chain, {}, iter, gen, state)
end

But of course without going through the intermediate table (or doing the reduction) - which might be large, time consuming or even infinite.

IMO, chain_from_iterable is more natural and can easily be used to implement chain = function(...) return chain_from_iterable({...}) end, but not the other way round.

list comprehensions

with this function, you can implement the bind operation of monads (i.e. Haskell's >>=) like this:

function bind(x, f)
  return chain_from_iterable(map(f, x))
end
getmetatable((wrap({}))).__index.bind = bind

which allows to write something like list comprehensions

function even(n) return n%2 == 0 end

range(10):filter(even):bind(function(a) return
  range(a):map(function(b) return
    a*b
  end)
end):each(print)

corresponding to a generator expression such as this:

(a*b
 for a in range(10)
 if a%2 == 0
 for b in range(a))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants