Women in Technology

Hear us Roar



Article:
  An Introduction to Haskell, Part 1: Why Haskell
Subject:   List comprehension in python
Date:   2007-05-24 05:33:37
From:   Skink
To filter the even number in Python I would have used :


even_list = [i for i in [1,2,3,4,5,6,7,8,9,10] if i % 2 == 0]


or even better :


even_list = [i for i in range(1,11) if i % 2 == 0]

Full Threads Newest First

Showing messages 1 through 5 of 5.

  • List comprehension in python
    2007-05-24 07:52:54  llimllib [View]

    Or, to ape the Haskell functional application:

    from functools import partial 
    def even(n): return n%2 == 0

    evens = partial(filter, even)
    evens(range(1,11))
  • List comprehension in ruby too...
    2007-05-24 08:11:27  pmccann [View]

    The ruby's also a little funked: maybe something like...

    (1..10).find_all {|i| i % 2 == 0}
    • List comprehension in ruby too...
      2007-05-25 12:24:06  PaulBattley [View]

      You could also do it like this, to make it a bit more explicit:

      even = lambda{ |x| x % 2 == 0 }
      (1..10).select(&even)

      But it's more elegant in Haskell.
    • List comprehension in ruby too...
      2007-05-26 03:23:29  paulk_asert [View]

      The Groovy equivalent to this looks very similar:

      (1..10).findAll {i -> i % 2 == 0}

      but if you look here:

      http://groovy.codehaus.org/Functional+Programming

      You can define the infinite stream of natural numbers which then lets you define all the even numbers as follows:

      def evennumbers = naturalnumbers.filter{ it % 2 == 0 }

      and then use it like this:

      assert [2 4 6 8 10] == evennumbers.take(5)
    • While we're picking apart the examples...
      2007-05-28 14:45:08  Yakshavers [View]

      The C example takes the cake. How is the caller supposed to know how many elements are in the returned array, so as to avoid a buffer overrun?