LangageFonctionnel

[wiki: Programmation fonctionnelle]

—-

Fonctions anonymes

#!comment
ATTENTION : l'abus de fonctions lambda obscurcit le code…
a creuser : http://docs.python.org/3/howto/functional.html
  • Le mot-clé lambda permet de créer une fonction anonyme et jetable.
  • L’instruction return est implicite.
  • On peut avoir plusieurs arguments.
#!python


>>> (lambda a: a**2)(2)
4
>>> f = lambda a: a**2
>>> f(2)
4
>>> def power(n):
... return lambda m: m**n
>>> p3 = power(3)
>>> p3(2)
8
>>> power(3)(2)
8


—-

Compréhensions de listes

#!python


>>> [ abs(x) for x in xrange(-2,2) ]
[ 2, 1, 0, 1 ]

>>> [ x for y in range(2,5) for x in range(y) ]
[ 0, 1, 0, 1, 2, 0, 1, 2, 3 ]

>>> [ x for x in range(-5,5) if x>0 ]
[ 1, 2, 3, 4 ]


—-

References

—-