Quantcast
Channel: Ok, panico » Funzionali
Viewing all articles
Browse latest Browse all 8

Functional Programming in Python di David Mertz

$
0
0

1500C’è chi dice che venerdì 17, la versione nazionale del più qualificato e universale venerdì 13 porti spheega. Ma forse no, se non ci credi.

Prendi per esempio l’ultimo, quello di luglio dove è saltato fuori un tweet on writing shorter & less bug-prone Python code, questo.

David è un cubano di San Francisco (quella della Bay Area, certo, in cima a Silicon Valley) che si autodefinisce an ideational bricoleur.  Su Twitter non è che è molto attivo, ma se continua e s’impegna lo followerò, promesso.

Per intanto il malloppo (no, dai sintetico 49 pagine in tutto comprese copertine, legalesismi e simili) moolto accattivante. Roba che mi viene voglia di farne un riassunto, chissà che non riesca a invogliarvi al linguaggio e al modo di codificare funzionalmente.

Parte subito con la definizione di programmazione funzionale (FP) in modo sensato, io non avrei saputo far meglio :lol:

Personally, I would roughly characterize functional programming as
having at least several of the following characteristics. Languages
that get called functional make these things easy, and make other
things either hard or impossible:

  • Functions are first class (objects). That is, everything you can do with “data” can be done with functions themselves (such as passing a function to another function).
  • Recursion is used as a primary control structure. In some languages, no other “loop” construct exists.
  • There is a focus on list processing (for example, it is the source of the name Lisp). Lists are often used with recursion on sublists as a substitute for loops.
    “Pure” functional languages eschew side effects. This excludes the almost ubiquitous pattern in imperative languages of assigning first one, then another value to the same variable to track the program state.
  • Functional programming either discourages or outright disallows statements, and instead works with the evaluation of expressions (in other words, functions plus arguments). In the pure case, one program is one expression (plus supporting definitions).
  • Functional programming worries about what is to be computed rather than how it is to be computed.
  • Much functional programming utilizes “higher order” functions (in other words, functions that operate on functions that operate on functions).

Naturalmente il grado di FP varia, i puristi forse esagerano e comunque Python is most definitely not a “pure functional programming language”; side effects are widespread in most Python programs. That
is, variables are frequently rebound, mutable data collections often
change contents, and I/O is freely interleaved with computation. It is
also not even a “functional programming language” more generally.
However, Python is a multiparadigm language that makes functional
programming easy to do when desired, and easy to mix with other
programming styles.

Ma per chi non è un purista estremista (dai io vengo (nel senso che ho cominciato) dal Fortran per dire!) e allora … :grin:

David ci introduce a Multiple Dispatch di Matthew Rocklin, credo di averla già indicata, se no lo faccio adesso, come the best current implementation of the concept it implements.

Adesso andate a leggere di là ma prima vorrei farvi notare che certe licenze ortografiche che uso non sono mie, p.es. pyrsisten, toolz et al.

Poi una ciliegia tira l’altra e in men che non si dica ci troviamo in Charming Python (no, non metto il link, è di là).

Tutto questo nella prefazione, in attesa del primo capitolo con un titolo non meno astoundingcente: (Avoiding) Flow Control. Forse sapete già da come ho cominciato, e qui vi confesso che sono contento che ero seduto quando l’ho visto :wink:

Qui si illustrano i costrutti tipici di FP, con esempi, quali l’encapsulation, la comprehension, la ricorsione, come eliminare i cicli (loops) con la funzione map().
Anche la ricorsione si può a volte fare senza ricorsione, p.es. con reduce().

Il capitolo 2, Callables passa in rassegna i diversi modi di chiamata di funzione (con Python), ci sono le lambda, i @decoratori, le closures e altre bestie che voi imperativi… Ma che diventano presto cose sensate e indispensabili.

Siamo così pronti alla Lazy Evaluation, fare solo quando serve, proprio come Haskell (e me).

Qui per non non haskellisti c’è da masterizzare un po’ di cose nuove, here is a quick example of combining a few things. Rather than the stateful Fibonacci class to let us keep a running sum, we might simply create a single lazy iterator to generate both the current number and this sum:

def fibonacci():
    a, b = 1, 1
    while True:
        yield a
        a, b = b, a + b

from itertools import tee, accumulate
s, t = tee(fibonacci())
pairs = zip(t, accumulate(s))
for _, (fib, total) in zip(range(7), pairs):
    print(fib, total)

fp-fib

Figuring out exactly how to use functions in itertools correctly and optimally often requires careful thought, but once combined, remarkable power is obtained for dealing with large, or even infinite, iterators that could not be done with concrete collections.

The documentation for the itertools module contain details on its combinatorial functions as well as a number of short recipes for combining them.

Tutto da assimilare, diverse funzioni che devono diventare abituali :grin.

E adesso siamo pronti per le Higher-Order Functions (HOFs). In general, a higher-order function is simply a function that takes one or more functions as arguments and/or produces a function as a result. Many interesting abstractions are available here. They allow chaining and combining higher-order functions in a manner analogous to how we can combine functions in itertools to produce new iterables.

E si finisce con i @decorators, ecco questi per me sono ancora un po’ nuovi; ma ci sto lavorando, nèh!

Intanto il book finisce con indicazioni più sensate su David, rockz!

:mrgreen:


Archiviato in:Funzionali, Linguaggi, Python

Viewing all articles
Browse latest Browse all 8

Latest Images

Trending Articles