Skip to content

Instantly share code, notes, and snippets.

@r4dian
Forked from tommorris/gist:284380
Last active May 4, 2017 11:13
Show Gist options
  • Save r4dian/02c693cabaca7a211769feafdf29a2ff to your computer and use it in GitHub Desktop.
Save r4dian/02c693cabaca7a211769feafdf29a2ff to your computer and use it in GitHub Desktop.
map/filter an array: spot the odd one out (I had to edit the python one to use map/filter, it was bothering me)
[1, 2, 3, 4, 5].map {|i| i * 2 }.find_all {|i| i > 5 }
# I have started monkey-patching `alias_method :filter, :find_all` in Array.
List(1, 2, 3, 4, 5).map(_ * 2).filter(_ > 5)
<?php
array_filter(
array_map( function($x) { return $x * 2; }, array(1, 2, 3, 4, 5)),
function($x) { if ($x > 5) { return true; } else { return false; } }
);
/* Here's the result:
Array
(
[2] => 6
[3] => 8
[4] => 10
)
What's going on here? Oh yeah, it's called PHP being shit. Having mapped and filtered
our array, it now returns us an array with all the key values being wrong. To access
the first value of this new array, instead of using [0], one must now use [2].
Gotta love the lack of distinction between associative arrays and lists in this
failure of a language.
Still, good on the PHP team for adding closures to PHP 5.3. */
?>
list( filter((lambda x: x > 5), map((lambda x: x*2), [1,2,3,4,5] )))
(filter (fn [x] (> x 5))
(map (fn [x] (* x 2)) (list 1 2 3 4 5)))
[1, 2, 3, 4, 5].map(function(x) { return x * 2; }).filter(function(x) { return (x > 5); });
new[] {1, 2, 3, 4, 5}.Select(x => x * 2).Where(x => x > 5);
grep { $_ > 5 } map { $_ * 2 } ( 1 .. 5 );
# thanks to @dorward for this.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment