4 ms·
> Here's a question, though: If your language did not support list comprehensions, what would it take to add them? For a language like Ruby, you may have to dig
by philwelch 14y ago
> Here's a question, though: If your language did not support list comprehensions, what would it take to add them? For a language like Ruby, you may have to dig into the language implementation itself.
No, not really:
http://stackoverflow.com/questions/310426/list-comprehension-in-ruby http://stackoverflow.com/questions/310426/list-comprehension...
- zachallaun 14y agoVery cool! I'm not completely sure how it would support comprehensions over more than one list, though (as in the permutations example).
- Rayne 14y agoThe point of a list comprehension is often that it can work with multiple lists. This can't do that, can it?
- listcomp 14y agoThat can't, but with https://gist.github.com/605891 https://gist.github.com/605891 you can, using syntax like: [(1..6),(4..6),(7..9)].comprehension { |a, b, c| a + b + c if a % 2 == 0 } And if you go to extremes like https://gist.github.com/3356675 https://gist.github.com/3356675 you can use Haskell-like syntax: [a + b | a <- ['n','p'..'t'], b <- %w[a i u e o]] Ruby's blocks and method_missing are very powerful.
- zachallaun 14y agoThat second example is awesome! And it demonstrates that I don't know nearly enough about Ruby. :) Thanks for contributing it.
- listcomp 14y agoYou're welcome! Just to be clear, I am not the original author. I was impressed with it myself. :)
- draegtun 14y agoVery nice indeed. NB. Correction to my earlier comment elsewhere here about List::Gen & multiple lists because it does provide cross combinators and also gather/take which is a perl6 way of doing complicated (multi) list comprehensions. Here are the two examples written in perl6 (which do work in Rakudo). gather for 1..6 X 4..6 X 7..9 -> $a, $b, $c { take $a + $b + $c if $a %% 2 } gather for ('n', 'p'..'t') X <a i u e o> -> $a, $b { take $a ~ $b }
- draegtun 14y agoDitto for Perl with modules like List::Maker and List::Gen. However like the Ruby example this only works on a single list. Which reminds me that I keep meaning to write a port of CL loop in Perl using Devel::Declare. ref: https://metacpan.org/module/List::Maker https://metacpan.org/module/List::Maker | https://metacpan.org/module/List::Gen https://metacpan.org/module/List::Gen | https://metacpan.org/module/Devel::Declare https://metacpan.org/module/Devel::Declare