[Haskell-cafe] Python?
Pierre Barbier de Reuille
pierre.barbier at cirad.fr
Wed May 11 03:26:02 EDT 2005
Daniel Carrera a écrit :
> Quinn Dunkan wrote:
>
>> Python has first class functions and lexical scoping, and encourages
>> higher-order functions, though to a much lesser degree than a real
>> functional language.
>
>
> I was surprised to hear about first class functions and higher order
> functions. So I googled for a bit, and I found something neat:
>
> ---<snip>---
> # Python implementation of Common Lisp's remove_if
> def remove_if(predicate, lst):
> return [elem for elem in lst if not predicate(elem)]
>
> print remove_if(lambda x:x % 2, [1,2,3,4,5,6,7,8])
> ---<snip>---
>
> This is so cool. So there we have a higher order function, passing a
> funtion as an argument, and even lambda notation. Neat.
Well, I would not recommand using lambda functions ! The main reason is
they are limited in that they only accept expressions (ie. not
statements) and you can end up with very ugly things (mainly because of
the lack of if-expressions).
Better use local functions for the same goal ! So your example becomes:
>>> def is_even(x):
... return x%2
>>> print remove_if(is_even, [1,2,3,4,5,6,7,8])
Or even better:
>>> def is_even(x):
... return x%2
>>> print remove_if(is_even, xrange(1,9))
And as local functions have lexical closure this is very interesting
(much more than lambda).
>
>
>> It is very natural to
>> write in a somewhat functional style, especially in regards to
>> sequence processing: higher order functions and listcomps provide the
>> processing and its built in generators and iterator protocol provide
>> some of the benefits of laziness.
>
>
> Hhhmmm.. I guess the above is also an example of that.
>
> [snip: lots of very interesting info I didn't know about]
>
> Thank you for all the information. I learned a lot today. I had no idea
> that Python had these features.
>
> Cheers,
> Daniel.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
--
Pierre Barbier de Reuille
INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France
tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68
More information about the Haskell-Cafe
mailing list