Skip to content

Instantly share code, notes, and snippets.

@lfborjas
Created February 8, 2011 23:12
Show Gist options
  • Save lfborjas/817504 to your computer and use it in GitHub Desktop.
Save lfborjas/817504 to your computer and use it in GitHub Desktop.
Filter even numbers in a list; fork it for maximum fun!
#these are meant to be run in a REPL, and the java one in beanshell of something of the sort:
#ruby
[1,2,3,4].select{ |x| x.even? }
#python
[x for x in [1,2,3,4] if not x%2]
#or, more norvingly
filter(lambda x: not x%2, [1,2,3,4])
#clojure
(filter #(even? % ) [1 2 3 4])
#but we don't need the wrapper (thanks to the guys in hackernews:)
(filter even? [1 2 3 4])
#scheme
(filter (lambda (x) (even? x)) '(1 2 3 4))
#same here:
(filter even? '(1 2 3 4))
#common lisp
(remove-if-not (lambda (x) (evenp x)) '(1 2 3 4))
#and here:
(remove-if-not 'evenp '(1 2 3 4))
#javascript
[1,2,3,4].filter(function(x){return !(x%2)})
#java
import java.util.ArrayList;
import java.util.Arrays;
public class filter {
public static void main (String [] args)
{
Integer [] a = {1,2,3,4};
System.out.println(
new ArrayList<Integer>(Arrays.asList(a)){{
ArrayList<Integer> clon = (ArrayList<Integer>)this.clone();
for(Integer e : clon){
if(e.intValue()%2 != 0)
this.remove(e);
}
}}
);
}
}
#After reading comments here and on HN, I now see that trying to *remove* stuff (filter-out) in hopes
#of mimicking how it _looks_ in other languages is stupid, even the lisps are actually building a new list
#recursively, so, here's a java version (which I took from the commments below) which is much more
#idiomatic and fair, as it accomplishes the same as the others: not using more than one explicit variable, #and that one, bound:
public class filter {
public static void main (String [] args)
{
System.out.println(
new java.util.ArrayList(){{
for(Integer e : new Integer[]{1,2,3,4})
if(e%2 == 0) this.add(e);
}}
);
}
}
@lfborjas
Copy link
Author

lfborjas commented Feb 9, 2011

@kennethreitz they're are meant to be run in a REPL, but @qpliu 's example seems to be able to run in beanshell's quasi-REPL, so you can remove the println if you want to :)

@qpliu you sir, are a genius, the most concise response I've seen so far and it's not obfuscated nor hard to understand, kudos!

@lfborjas
Copy link
Author

lfborjas commented Feb 9, 2011

Thanks @afeinberg , I had the suspicion that it the quoting of even? wasn't standard, it didn't seem right. It works on GNU CLisp, though.

@aero
Copy link

aero commented Feb 9, 2011

Perl

grep { not $_%2 } 1..4

grep { !($_%2) } 1..4

grep { ($_+1)%2 } 1..4

grep !($_%2), 1..4

@fcostin
Copy link

fcostin commented Feb 9, 2011

R

Filter(function(x) !(x%%2), c(1, 2, 3, 4))

I'm pretty new to R, so it took me a minute to figure out it was %% (yuck!) not %, and perhaps it can be shorter ...

@kbob
Copy link

kbob commented Feb 9, 2011

C++

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

using namespace std;

template <typename Integral>
class counter {
public:
    typedef Integral result_type;
    counter(Integral start) : n(start) {}
    result_type operator()() { return n++; }
private:
    result_type n;
};

int main()
{
    vector<int> v;
    generate_n(back_inserter(v), 4, counter<int>(1));
    remove_copy_if(v.begin(), v.end(),
                   ostream_iterator<int>(cout, " "),
                   bind2nd(modulus<int>(), 2));
    return 0;
}

@lfborjas
Copy link
Author

lfborjas commented Feb 9, 2011

cool, finally some love for C++!

@mlaccetti
Copy link

Can always count on C++ to make Java look good? :)

@isaksky
Copy link

isaksky commented Feb 9, 2011

C#:
var list = new List() { 1, 2, 3, 4 }.FindAll(x => x % 2 == 0);

@lfborjas
Copy link
Author

lfborjas commented Feb 9, 2011

It would be nice to see it in C, using pointers to functions to define a custom filter (with void pointers too). Most of the above languages would be naught without C, anyways, hehe. I'm more than rusty in my C, which is sad :/

@nrkn
Copy link

nrkn commented Feb 9, 2011

C#, via Enumerable.Range

var filtered = Enumerable.Range( 1, 4 ).Where( x => x % 2 == 0 );

@tkay
Copy link

tkay commented Feb 9, 2011

Smalltalk
(1 to: 4) select: [:x| x even]

@theshock
Copy link

theshock commented Feb 9, 2011

Javascript 1.7

[x for each (x in [1,2,3,4]) if (x%2 == 0)]

Javascript 1.8

[1,2,3,4].filter(function(x) x%2 == 0)

@nllarson
Copy link

nllarson commented Feb 9, 2011

GROOVY

[1,2,3,4].findAll { it % 2 == 0 }

@qpliu
Copy link

qpliu commented Feb 9, 2011

C

#include <stdio.h>
#include <stdlib.h>

struct list {
      int i;
      struct list *next;
};

struct list *filter(int *a, int count, int test(int))
{
      int i;
      struct list *head, *list, *list2;
      if (count == 0)
              return NULL;
      head = malloc(sizeof(struct list));
      list = head;
      list2 = NULL;
      for (i = 0; i < count; i++) {
              if (test(a[i])) {
                      list->i = a[i];
                      list->next = malloc(sizeof(struct list));
                      list2 = list;
                      list = list->next;
              }
      }
      free(list);
      if (list2) {
              list2->next = NULL;
              return head;
      }
      return NULL;
}

void print(struct list *list)
{
      struct list *next;
      while (list) {
              printf(" %d", list->i);
              next = list->next;
              free(list);
              list = next;
      }
}

int even(int i)
{
      return i%2 == 0;
}

int main()
{
      int a[4] = { 1, 2, 3, 4 };
      print(filter(a, 4, even));
}

And another imperative Haskell
import Data.IORef
main = do { a <- newIORef [1..4]; b <- newIORef []; l <- fmap length (readIORef a); r <- fmap (snd . head . dropWhile (not . null . fst)) (sequence $ replicate l (do { (i:as) <- readIORef a; if even i then modifyIORef b (++[i]) else return (); writeIORef a as; bs <- readIORef b; return (as,bs) })); print r }

@lfborjas
Copy link
Author

lfborjas commented Feb 9, 2011

holy crap, in C with a linked list implementation baked in; now that's a really cool solution!

@nrkn
Copy link

nrkn commented Feb 9, 2011

C#, using extension methods

using System;
using System.Collections.Generic;
using System.Linq;

static class Filter {
  static void Main() {
    //just getting the filtered list would look like:
    //var filtered = 1.To( 4 ).Where( Even );

    1.To( 4 ).If( Even, Console.WriteLine );
  }

  static IEnumerable<int> To( this int i, int to ) {
    return Enumerable.Range( i, to - i + 1 );
  }

  static void If<T>( this IEnumerable<T> enumerable, Func<T,bool> predicate, Action<T> action ) {
    enumerable.Where( predicate ).ToList().ForEach( action );
  }

  static bool Even( this int i ) {
    return i % 2 == 0;
  }
}

@skbach
Copy link

skbach commented Feb 9, 2011

javascript 1.8

[1,2,3,4].filter(function (x) !(x%2))

@aalmiray
Copy link

aalmiray commented Feb 9, 2011

Groovy

(1..4).findAll { !(it%2) }

(1..4).grep { !(it%2) }

@pjmlp
Copy link

pjmlp commented Feb 9, 2011

C++

An improved C++ version:

#include <list>
#include <algorithm>
#include <iostream>
#include <iterator>


using namespace std;

int main (void)
{
    list<int> numbers = {1,2,3,4};
    remove_copy_if(numbers.begin(), numbers.end(), ostream_iterator<int>(cout, " "), [](int x) {return x % 2;});
}

@guilleiguaran
Copy link

Scala

  (1 to 4).filter(_ % 2 == 0)

@nedbrek
Copy link

nedbrek commented Feb 10, 2011

Tcl

Tcl lacks a built-in filter function, but it is easy to write:

proc filter {list script} {
   set res ""
   foreach e $list {if $script {lappend res $e}}
   return $res
}

Then you have:
filter {1 2 3 4 5} {($e & 1)==0}

@rep-movsd
Copy link

More succinct C++ version

#include <algorithm>
#include <iostream>
#include <iterator>

using namespace std;

int main (void)
{
    int nums[] = {1,2,3,4};
    remove_copy_if(nums, nums + 4, ostream_iterator<int>(cout, " "), [](int x) {return x % 2;});
    return 0;
}

@embuc
Copy link

embuc commented Nov 21, 2016

Oh, well:

Java:

Arrays.asList(1,2,3,4).stream().filter((i)-> i%2==0).collect(toList());

@GraniteConsultingReviews

I have a problem in a loop while compiling this code giving error in this portion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment