Talk:List comprehensions: Difference between revisions

→‎Ruby notes: new section
(→‎Ruby notes: new section)
Line 45:
There are several that make no attempt at following set-builder notation. (Maybe turn them into an omit from) --[[User:Paddy3118|Paddy3118]] 16:30, 16 November 2009 (UTC)
:That seems OK. "List comprehension" is really about the shorthand syntax, so examples that need explicit loops for this should removed. The omit option is best I think. Just make sure you keep examples that use set-builder-like language instead of notation. --[[User:Mwn3d|Mwn3d]] 16:36, 16 November 2009 (UTC)
 
== Ruby notes ==
 
Before I edited the page, the Ruby code used Enumerable#collect (also known as Enumerable#map) and Array#compact.
 
<lang ruby># no temp array, but a lot of housework to flatten and remove nils
(1..n).collect {|x| (1..n).collect {|y| (1..n) \
.collect {|z| [x,y,z] if x**2 + y**2 == z**2}}} \
.reduce(:+).reduce(:+).compact</lang>
 
I changed this to a mess involving Enumerable#flat_map and Enumerable#select, but have now simplified the code by using Array#keep_if.
 
<lang ruby>r = ((1..n).flat_map { |x|
(x..n).flat_map { |y|
(y..n).flat_map { |z|
[[x, y, z]].keep_if { x * x + y * y == z * z }}}})</lang>
 
The above code is now on the page. Contrast the below code, which uses Range#each (like 'for' loops in other languages) and Array#<< to append to an array.
 
<lang ruby>r = [] # start with an empty array
(1..n).each { |x|
(x..n).each { |y|
(y..n).each { |z|
r << [x, y, z] if x * x + y * y == z * z }}}</lang>
 
--[[User:Kernigh|Kernigh]] 04:38, 4 February 2011 (UTC)
Anonymous user