Racket – espressioni e definizioni – 7

8bContinuando da qui sto copiando da [doc]/guide/scheme-forms.html

Non so se si dice (Sergio?) ma sapete che io (me) certe cose le faccio comunque (CMQ).

Quotare: quote e '

The quote form produces a constant:

(quote datum)

The syntax of a datum is technically specified as anything that the read function parses as a single element. The value of the quote form is the same value that read would produce given datum.

The datum can be a symbol, a boolean, a number, a (character or byte) string, a character, a keyword, an empty list, a pair (or list) containing more such values, a vector containing more such values, a hash table containing more such values, or a box containing another such value.

ed63

As the last example above shows, the datum does not have to match the normalized printed form of a value. A datum cannot be a printed representation that starts with #<, so it cannot be #<void>, #<undefined>, or a procedure.

The quote form is rarely used for a datum that is a boolean, number, or string by itself, since the printed forms of those values can already be used as constants. The quote form is more typically used for symbols and lists, which have other meanings (identifiers, function calls, etc.) when not quoted.

An expression

'datum

is a shorthand for

(quote datum)

and this shorthand is almost always used instead of quote. The shorthand applies even within the datum, so it can produce a list containing quote.

ed64

Notare l’ultima form; ma c’è un quirk sotto

ed65

Quasiquotare: quasiquote e `

Per Linux con la tastiera italiana ` si ottiene con AltGr + '; per chi usa Window$ invece Alt + 96 da tastierino numerico (se c’è, spheegati!).

The quasiquote form is similar to quote:

(quasiquote datum)

However, for each (unquote expr) that appears within the datum, the expr is evaluated to produce a value that takes the place of the unquote sub-form.

ed66

This form can be used to write functions that build lists according to certain patterns.

ed67

Or even to cheaply construct expressions programmatically. (Of course, 9 times out of 10, you should be using a macro to do this (the 10th time being when you’re working through a textbook like PLAI).)

Nota: uh! mi sa che, cioè, sì, prossimamente, probabilmente…
Tornando al dunque:

ed68

Vediamo se ho capito:

ed69

:grin: a volte il prof si diverte, controlla come copiate :wink:

The unquote-splicing form is similar to unquote, but its expr must produce a list, and the unquote-splicing form must appear in a context that produces either a list or a vector. As the name suggests, the resulting list is spliced into the context of its use.

ed70

Using splicing we can revise the construction of our example expressions above to have just a single let expression and a single + expression.

ed71

E qui si potrebbe ri-valutare la form:

ed72

Nota per me: λ è una funzione di Racket (ok, si dovrebbe dire procedure nella parlance del linguaggio) che (indovina?) è identica a lambda. Scrivere λ con Linux non è impossibile ma richiede una certa coordinazione dei diti: Shit+Ctrl+U e poi 03bb, così λ :wink:

ed73

If a quasiquote form appears within an enclosing quasiquote form, then the inner quasiquote effectively cancels one layer of unquote and unquote-splicing forms, so that a second unquote or unquote-splicing is needed.

ed74

Nota: la REPL usa le shorthands per quasiquote e unquote, proprio come dice il prof: the shorthand form of quasiquote and unquote will be used: ` (i.e., a backquote) and , (i.e., a comma). The same shorthands can be used in expressions:

ed75

The shorthand form of unquote-splicing is ,@:

ed76

Pausa :mrgreen:

Aiuta un amico

FSF30Ecco un’idea bellissimissima. Viene da FSF, Free Software Foundation che li di idee belle ne trovi tante.

Ci sono tante cose che non vanno, questo è un blog di informatica e dintorni (Insalate di cibernetica recita il banner) e allora ci limitiamo alla strage che Micro$oft sta compiendo in questi giorni (più di 10 milioni di infettati nel primo giorno mi dicono). Allora ecco:

We can’t stop all the millions of people who are installing Windows 10 right now, but we can influence our friends and family to skip Windows and join us in the free world. As you know, Windows 10 puts those that use it under the thumb of Microsoft, while free software treats users as equals and gives them control over their digital lives.

Continua qua: Help a friend skip Windows 10 and try GNU/Linux.

luigiSe poi volete essere davvero über-coscienziosi c’è Lubit, nèh!

Racket – espressioni e definizioni – 6

l0Ancora qui [doc]/guide/scheme-forms.html proseguendo da qui.

Assegnamento: set!

Assign to a variable using set!:

(set! id expr)

A set! expression evaluates expr and changes id (which must be bound in the enclosing environment) to the resulting value. The result of the set! expression itself is #<void>.

ed49

Uhmmm… qui parecchi cambiamenti rispetto a CL. Di là c’è set, setf, setq, e forse altro ancora che assegnano un valore a una variabile anche nuova. Qui invece siamo in ambito funzionale, la variabile (mutable value o mutation) dev’essere presente, definita con define e set! le assegna solo il valore. L’esempio è meno bello del solito: la lista greeted è un side-effect della funzione greet. Ma non eravamo in ambito funzionale? :roll:
Questa nota è anche polemica ma solo perché la documentazione di Racket è eccezionale (e oggi che posso lamentarmi lo faccio) :wink:

ed50

Anche qui side-effect: la variabile locale n definita in make-running-total conserva il suo valore per chiamate successive ed è (ovviamente) diversa per funzioni diverse. Sai ‘na roba? non è molto ‘mericano ma mi viene la voglia di un’aggiunta:

ed51

Linee guida per gli assegnamenti

Although using set! is sometimes appropriate, Racket style generally discourages the use of set!. The following guidelines may help explain when using set! is appropriate.

1. As in any modern language, assigning to a shared identifier is no substitute for passing an argument to a procedure or getting its result.

Really awful example:

ed52

Ok example:

ed53

2. A sequence of assignments to a local variable is far inferior to nested bindings.

Bad example:

ed54

Ok example:

ed55

Notare che in questo caso non si usa set!.

3. Using assignment to accumulate results from an iteration is bad style. Accumulating through a loop argument is better.

Somewhat bad example:

ed56

Ok example:

ed57

Better (use an existing function) example:

ed58

(quello che avevo pensato io).

Good (a general approach) example:

ed59

for/fold e in-list sono nuove, prossimamente (forse).

4. For cases where stateful objects are necessary or appropriate, then implementing the object’s state with set! is fine.

Ok example:

ed60

All else being equal, a program that uses no assignments or mutation is always preferable to one that uses assignments or mutation. While side effects are to be avoided, however, they should be used if the resulting code is significantly more readable or if it implements a significantly better algorithm.

The use of mutable values, such as vectors and hash tables, raises fewer suspicions about the style of a program than using set! directly. Nevertheless, simply replacing set!s in a program with vector-set!s obviously does not improve the style of the program.

Valori multipli: set!-values

The set!-values form assigns to multiple variables at once, given an expression that produces an appropriate number of values:

(set!-values (id ...) expr)

This form is equivalent to using let-values to receive multiple results from expr, and then assigning the results individually to the ids using set!.

ed61

Uhmmm… perché lo swap?

ed62

sì, funziona ancora; poi il begin0 ritorna la prima form. Insomma dubbio.

:mrgreen:

Racket – espressioni e definizioni – 5

pe1Sono qui [doc]/guide/scheme-forms.html continuando da qui.

Istruzioni condizionali

Di là è solo conditionals ma mi suona strano in italiano, sapete che sono vecchio :wink:

Most functions used for branching, such as < and string?, produce either #t or #f. Racket’s branching forms, however, treat any value other than #f as true. We say a true value to mean any value other than #f.

This convention for “true value” meshes well with protocols where #f can serve as failure or to indicate that an optional value is not supplied. (Beware of overusing this trick, and remember that an exception is usually a better mechanism to report failure.)

For example, the member function serves double duty; it can be used to find the tail of a list that starts with a particular item, or it can be used to simply check whether an item is present in a list:

ed39

Scelta semplice: if

Il termine usato nella documentazione è branching, non so tradurlo in italiano.

In an if form,

(if test-expr then-expr else-expr)

the test-expr is always evaluated. If it produces any value other than #f, then then-expr is evaluated. Otherwise, else-expr is evaluated.

An if form must have both a then-expr and an else-expr; the latter is not optional. To perform (or skip) side-effects based on a test-expr, use when or unless, which we describe later.

Combinare i test: and e or

Racket’s and and or are syntactic forms, rather than functions. Unlike a function, the and and or forms can skip evaluation of later expressions if an earlier one determines the answer.

(and expr ...)

An and form produces #f if any of its exprs produces #f. Otherwise, it produces the value of its last expr. As a special case, (and) produces #t.

(or expr ...)

The or form produces #f if all of its exprs produce #f. Otherwise, it produces the first non-#f value from its exprs. As a special case, (or) produces #f.

ed40

If evaluation reaches the last expr of an and or or form, then the expr’s value directly determines the and or or result. Therefore, the last expr is in tail position, which means that the above got-milk? function runs in constant space.

Tail Recursion [qui] introduces tail calls and tail positions.

Concatenare tests: cond

The cond form chains a series of tests to select a result expression. To a first approximation, the syntax of cond is as follows:

(cond [test-expr body ...+]
      ...)

Each test-expr is evaluated in order. If it produces #f, the corresponding bodys are ignored, and evaluation proceeds to the next test-expr. As soon as a test-expr produces a true value, its bodys are evaluated to produce the result for the cond form, and no further test-exprs are evaluated.

The last test-expr in a cond can be replaced by else. In terms of evaluation, else serves as a synonym for #t, but it clarifies that the last clause is meant to catch all remaining cases. If else is not used, then it is possible that no test-exprs produce a true value; in that case, the result of the cond expression is #<void>.

ed41

notare il secondo test :wink:

ed42

The full syntax of cond includes two more kinds of clauses:

(cond cond-clause ...)
         
  cond-clause = [test-expr then-body ...+]
              |	[else then-body ...+]
              |	[test-expr => proc-expr]
              |	[test-expr]

The => variant captures the true result of its test-expr and passes it to the result of the proc-expr, which must be a function of one argument.

ed43

A clause that includes only a test-expr is rarely used. It captures the true result of the test-expr, and simply returns the result for the whole cond expression.

Creare sequenze

Indovina? sarebbe sequencing :wink:

Racket programmers prefer to write programs with as few side-effects as possible, since purely functional code is more easily tested and composed into larger programs. Interaction with the external environment, however, requires sequencing, such as when writing to a display, opening a graphical window, or manipulating a file on disk.

begin

A begin expression sequences expressions:

(begin expr ...+)

The exprs are evaluated in order, and the result of all but the last expr is ignored. The result from the last expr is the result of the begin form, and it is in tail position with respect to the begin form.

ed44

Many forms, such as lambda or cond support a sequence of expressions even without a begin. Such positions are sometimes said to have an implicit begin.

ed45

The begin form is special at the top level, at module level, or as a body after only internal definitions. In those positions, instead of forming an expression, the content of begin is spliced into the surrounding context.

ed46

Uhmmm… sì ma… OK, aspetta: This splicing behavior is mainly useful for macros, prossimamente.

begin0

A begin0 expression has the same syntax as a begin expression:

(begin0 expr ...+)

The difference is that begin0 returns the result of the first expr, instead of the result of the last expr. The begin0 form is useful for implementing side-effects that happen after a computation, especially in the case where the computation produces an unknown number of results.

ed47

when e unless

The when form combines an if-style conditional with sequencing for the “then” clause and no “else” clause:

(when test-expr then-body ...+)

If test-expr produces a true value, then all of the then-bodys are evaluated. The result of the last then-body is the result of the when form. Otherwise, no then-bodys are evaluated and the result is #<void>.

The unless form is similar:

(unless test-expr then-body ...+)

The difference is that the test-expr result is inverted: the then-bodys are evaluated only if the test-expr result is #f.

ed48

Continua, ma non subito, pausa :mrgreen:

Functional Programming in Python di David Mertz

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:

Racket – espressioni e definizioni – 4

kk7Oggi qui [doc]/guide/scheme-forms.html continuando da qui.

Collegamenti locali

Although internal defines can be used for local binding, Racket provides three forms that give the programmer more control over bindings: let, let*, and letrec.

Collegamento in parallelo: let

A let form binds a set of identifiers, each to the result of some expression, for use in the let body:

(let ([id expr] ...) body ...+)

The ids are bound “in parallel”. That is, no id is bound in the right-hand side expr for any id, but all are available in the body. The ids must be different from each other.

ed28

The fact that an id‘s expr does not see its own binding is often useful for wrappers that must refer back to the old value:

ed29

Uhmmm, non semplicissimo, ridefinisce la funzione + ma solo se x è una stringa. Da mettere nel cassetto delle cose lispiche.

Occasionally, the parallel nature of let bindings is convenient for swapping or rearranging a set of bindings:

ed30

The characterization of let bindings as “parallel” is not meant to imply concurrent evaluation. The exprs are evaluated in order, even though the bindings are delayed until all exprs are evaluated.

Collegamento sequenziale: let*

The syntax of let* is the same as let:

(let* ([id expr] ...) body ...+)

The difference is that each id is available for use in later exprs, as well as in the body. Furthermore, the ids need not be distinct, and the most recent binding is the visible one.

ed31

In other words, a let* form is equivalent to nested let forms, each with a single binding:

ed32

Ecco qui a me verrebbe da usare quasi sempre let*, chissà se…

Collegamento ricorsivo: letrec

The syntax of letrec is also the same as let:

(letrec ([id expr] ...) body ...+)

While let makes its bindings available only in the bodys, and let* makes its bindings available to any later binding expr, letrec makes its bindings available to all other exprs—even earlier ones. In other words, letrec bindings are recursive.

The exprs in a letrec form are most often lambda forms for recursive and mutually recursive functions:

ed33

e adesso andiamo con un esempio lungo:

ed34

ma se creo il file tarzan nella dir corrente (ecco perché 'orig-dir) ottengo:

ed35

Sì, macchinoso :roll:

While the exprs of a letrec form are typically lambda expressions, they can be any expression. The expressions are evaluated in order, and after each value is obtained, it is immediately associated with its corresponding id. If an id is referenced before its value is ready, an error is raised, just as for internal definitions.

ed36

let con nome

A named let is an iteration and recursion form. It uses the same syntactic keyword let as for local binding, but an identifier after the let (instead of an immediate open parenthesis) triggers a different parsing.

(let proc-id ([arg-id init-expr] ...)
  body ...+)

A named let form is equivalent to

(letrec ([proc-id (lambda (arg-id ...)
                     body ...+)])
  (proc-id init-expr ...))

That is, a named let binds a function identifier that is visible only in the function’s body, and it implicitly calls the function with the values of some initial expressions.

ed37

Valori multipli: let-values, let*-values, letrec-values

In the same way that define-values binds multiple results in a definition […] let-values, let*-values, and letrec-values bind multiple results locally.

(let-values ([(id ...) expr] ...)
  body ...+)

(let*-values ([(id ...) expr] ...)
  body ...+)

(letrec-values ([(id ...) expr] ...)
  body ...+)

Each expr must produce as many values as corresponding ids. The binding rules are the same for the forms without -values forms: the ids of let-values are bound only in the bodys, the ids of let*-values are bound in exprs of later clauses, and the ids of letrec-values are bound for all exprs.

ed38

Pausa :mrgreen:

Racket – espressioni e definizioni – 3

bb12Oggi qui [doc]/guide/scheme-forms.html proseguendo da qui.

Definizioni: define

A basic definition has the form

(define id expr)

in which case id is bound to the result of expr.

ed17

The define form also supports a shorthand for function definitions:

(define (id arg ...) body ...+)

which is a shorthand for

(define id (lambda (arg ...) body ...+))

ed18

The function shorthand via define also supports a rest argument (i.e., a final argument to collect extra arguments in a list):

(define (id arg ... . rest-id) body ...+)

which is a shorthand

(define id (lambda (arg ... . rest-id) body ...+))

ed19

Adesso sono nei guai: non so tradurre curry, specie quando declinato come aggettivo, portate pazienza :roll:
Poi, ripensandoci, lascio in inglese, tanto c’è lo spiegone.

Curried functions

Consider the following make-add-suffix function that takes a string and returns another function that takes a string:

ed20

Although it’s not common, result of make-add-suffix could be called directly, like this:

ed21

In a sense, make-add-suffix is a function takes two arguments, but it takes them one at a time. A function that takes some of its arguments and returns a function to consume more is sometimes called a curried function.

Using the function-shorthand form of define, make-add-suffix can be written equivalently as

ed22

This shorthand reflects the shape of the function call (make-add-suffix "!"). The define form further supports a shorthand for defining curried functions that reflects nested function calls:

ed23

The full syntax of the function shorthand for define is as follows:

(define (head args) body ...+)
 
  head = id
       | (head args)
 	 	 	 	 
  args = arg ...
       | arg ... . rest-id

The expansion of this shorthand has one nested lambda form for each head in the definition, where the innermost head corresponds to the outermost lambda.

Valori multipli e define-values

A Racket expression normally produces a single result, but some expressions can produce multiple results. For example, quotient and remainder each produce a single value, but quotient/remainder produces the same two values at once:

ed24

As shown above, the REPL prints each result value on its own line.

Multiple-valued functions can be implemented in terms of the values function, which takes any number of values and returns them as the results:

ed25

The define-values form binds multiple identifiers at once to multiple results produced from a single expression:

(define-values (id ...) expr)

The number of results produced by the expr must match the number of ids.

ed26

A define form (that is not a function shorthand) is equivalent to a define-values form with a single id.

Definizioni interne

Qui entriamo in una cosa lispica che a prima vista sembra difficile ma è quello che rende pheego il Lisp (e derivati).

When the grammar for a syntactic form specifies body, then the corresponding form can be either a definition or an expression. A definition as a body is an internal definition.

Expressions and internal definitions in a body sequence can be mixed, as long as the last body is an expression.

For example, the syntax of lambda is

(lambda (f)                ; no definitions
  (printf "running\n")
  (f 0))
     
(lambda (f)                ; one definition
  (define (log-it what)
    (printf "~a\n" what))
      (log-it "running")
    (f 0)
    (log-it "done"))
     
(lambda (f n)              ; two definitions
  (define (call n)
    (if (zero? n)
        (log-it "done")
        (begin
          (log-it "running")
          (f n)
          (call (- n 1)))))
  (define (log-it what)
    (printf "~a\n" what))
  (call n))

so the following are valid instances of the grammar:

(lambda gen-formals
  body ...+)

Internal definitions in a particular body sequence are mutually recursive; that is, any definition can refer to any other definition—as long as the reference isn’t actually evaluated before its definition takes place. If a definition is referenced too early, an error occurs.

ed27

A sequence of internal definitions using just define is easily translated to an equivalent letrec form ([prossimamente]). However, other definition forms can appear as a body, including define-values, struct ([prossimamente]) or define-syntax ([macros]).

Pausa (ci vuole, imho) :mrgreen:

Racket – espressioni e definizioni – 2

41208_450Oggi qui: [doc]/guide/scheme-forms.html continuando da qui.

lambda

A lambda expression creates a function. In the simplest case, a lambda expression has the form

(lambda (arg-id ...)
  body ...+)

A lambda form with n arg-ids accepts n arguments:

ed8

Dichiarare un argomento rest

Ieri l’ho detto che me l’aspettavo :grin:
A lambda expression can also have the form

(lambda rest-id
  body ...+)

That is, a lambda expression can have a single rest-id that is not surrounded by parentheses. The resulting function accepts any number of arguments, and the arguments are put into a list bound to rest-id.

ed9

Functions with a rest-id often use apply to call another function that accepts any number of arguments.

ed10

The lambda form also supports required arguments combined with a rest-id:

(lambda (arg-id ...+ . rest-id)
  body ...+)

The result of this form is a function that requires at least as many arguments as arg-ids,  and also accepts any number of additional arguments.

ed11

A rest-id variable is sometimes called a rest argument, because it accepts the “rest” of the function arguments.
È simile ma non identico alla versione di CL.

Dichiarare argomenti opzionali

Instead of just an identifier, an argument (other than a rest argument) in a lambda form can be specified with an identifier and a default value:

(lambda gen-formals
  body ...+)
 
  gen-formals = (arg ...)
              | rest-id
 	      | (arg ...+ . rest-id)
 	 	 	 	 
         arg = arg-id
 	 [arg-id default-expr]

An argument of the form [arg-id default-expr] is optional. When the argument is not supplied in an application, default-expr produces the default value. The default-expr can refer to any preceding arg-id, and every following arg-id must have a default as well.

ed12

Anche qui sintassi diversa (migliore) rispetto CL.

Dichiarare keyword arguments

A lambda form can declare an argument to be passed by keyword, instead of position. Keyword arguments can be mixed with by-position arguments, and default-value expressions can be supplied for either kind of argument:

(lambda gen-formals
  body ...+)
 
  gen-formals =	(arg ...)
 	      | rest-id
 	      |	(arg ...+ . rest-id)
 	 	 	 	 
          arg = arg-id
 	      |	[arg-id default-expr]
 	      |	arg-keyword arg-id
 	      | arg-keyword [arg-id default-expr]

An argument specified as arg-keyword arg-id is supplied by an application using the same arg-keyword. The position of the keyword–identifier pair in the argument list does not matter for matching with arguments in an application, because it will be matched to an argument value by keyword instead of by position.

ed13

An arg-keyword [arg-id default-expr] argument specifies a keyword-based argument with a default value.

ed14

The lambda form does not directly support the creation of a function that accepts “rest” keywords. To construct a function that accepts all keyword arguments, use make-keyword-procedure. The function supplied to make-keyword-procedure receives keyword arguments through parallel lists in the first two (by-position) arguments, and then all by-position arguments from an application as the remaining by-position arguments.

ed15

OK, introdotto cose nuove di soppiatto ma è chiaro :wink:

Funzioni dipendenti dall’arità: case-lambda

The case-lambda form creates a function that can have completely different behaviors depending on the number of arguments that are supplied. A case-lambda expression has the form

(case-lambda
  [formals body ...+]
  ...)
      
  formals = (arg-id ...)
          | rest-id
          | (arg-id ...+ . rest-id)

where each [formals body ...+] is analogous to (lambda formals body ...+). Applying a function produced by case-lambda is like applying a lambda for the first case that matches the number of given arguments.

ed16

A case-lambda function cannot directly support optional or keyword arguments.

Nota perso: sì ho solo copiato; in fondo-in fondo è tutto logico e semplice; poi quando si tratterà di usarla si dovrà consultare la guida (questo post).

:mrgreen:

Spyder, un IDE per Python

Spyder_logo

Sapete la serendipity, ricorsiva in questo caso. Recentemente un giovane volonteroso mi chiedeva quale IDE semplice usare per impratichirsi con Python. Io, dopo avergli ricordato che essedo vecchio uso un editor normale (Gedit, sì lo so che c’è di meglio) ho consigliato Geany. Che ogni tanto uso anch’io. E sì, c’è anche per Windows, cosa che in quel caso era necessaria.
Giovedì pomeriggio mi viene ripetuta la stessa richiesta. E io insisto con Geany.

E adesso chi glielo dice ai due? Sì perché ho trovato di meglio, grazie a un post che raccomanda Emacs: Emacs for Data Science.

Ma non voglio propagandare Emacs. Anche se è il migliore in assoluto, senza paragoni. Solo che per imparare a usarlo e sfruttare le sue possibilità ci vuole tempo e costanza e poi forse per le cose piccole non è necessario :roll: (Dai non infierite, a volte lo uso, per esempio con SLIME).

Spyder (formerly Pydee) is an open source cross-platform IDE for scientific programming in the Python language. Spyder integrates NumPy, SciPy, Matplotlib and IPython, as well as other open source software, dice la Wiki.

Una rapida occhiata alla pagina degli screenshots mi ha convinto a provarlo.

Per Ubuntu c’è nel Software Center, installo (per la versione 2.x ma c’è anche per la 3), 51 MB, ed ecco:

click per ingrandire

click per ingrandire

Nel terminale (ma non sono più obbligato a usarlo, cosa che genera lamentele per i windowsiani) ottengo:

con-fib

OK, l’esempio è semplicissimo, questo è il codice (fib.py):

# -*- coding: utf-8 -*-

def fibGen(n, a=0, b=1):
    print a, b,
    while n > 0:
        yield a
        a, b, n = b, a+b, n - 1
        print b,
        if (n % 5) == 0: print
#main
[i for i in fibGen(50)]

Ovviamente c’è molto di più, conviene leggere la documentazione, qui: Spyder – Documentation.
Il sito di Spyder è su GitHub.
E sì, dice come installarlo su Windows :grin:

Visto nel Web – 193

Continua a fare caldo :sad: Ma io ci sono, ci sono novità in arrivo (forse, ma non subito). Intanto ecco cosa ho visto nel Web.
Linus
git commit -m “Fixed interface issues.”

::: jonathansampson

Waybacklapse 2.0: A Python Wayback Machine Time-Lapse Creator (Now with Python3 and Docker!)
::: Kyle Purdon

A historical note from the 1984 preface to “Lisp Machine Manual”
::: btbytes

Silenzi che valgono come risposte
::: Tech Economy

The Best Programming Language is None
::: Bitbucket

backup

Numerators of harmonic numbers
con Python si possono fare cose che voi umani…
::: The Endeavour

SPIEGEL Interview with WikiLeaks Head Julian Assange
::: _arianna

Today in irony: Paper titled “Promoting an open research culture”
::: abigailStev

VERY happy with the future default #matplotlib colormap
::: astrofrog

Twitter: a cosa servono i Preferiti?
::: Downloadblog

CKwvapxW8AEAgMH

Oracle rilascia VirtualBox 5
::: lffl

GCC 5.2 Released
io ho il 4.9.2, sono vecchio :wink:
::: Slashdot

Keep the dream alive
::: yurrriq

Spam drops below 50% of email for the first time since 2003
::: EmileTrombetti

Next Nobel Prize
::: keul

just-cooking

Big tech companies back Samsung in court case against Apple
::: Engadget

Monoid
Open Source Coding Font
::: larsenwork

Compare and contrast: Apple and Microsoft
::: The Economist

The Seven Stages of SVG
::: codepen

Come la Cina censura WeChat
::: Chiusi nella rete

9e6ab51002520133f0f4005056a9545d

A group of wolves is called a pack
::: SkylerFoxy

Hackers Remotely Kill a Jeep on the Highway
::: taosecurity

Free Tools For Detecting Hacking Team Malware In Your Systems
::: Slashdot

We need to go beyond the web
::: Daniel Lemire

Gmail Spam Filter Changes Bite Linus Torvalds
::: Slashdot

IMG_1388

Ma questa menata dei cookie
::: DarioBressanini

Keyword Bookmarks for OpenStack Developers
::: Doug Hellmann

The Risks of Regulating Zero-Days
::: The Center for Internet and Society

Instagram: cosa succede quando vi chiamate come un vip? La storia di Andres Iniesta
::: Downloadblog

A che gioco sta giocando Twitter in Turchia? Ubbidisce e basta?
::: fabiochiusi

beretta

Your Timeline: Revisiting the world that you’ve explored
uhmmm…
::: Google

The Anatomy of a Puzzle
A Case Study In “Specification Driven Programming”
::: chriskohlhepp

44 anni di UNIX
::: SIAMO GEEK

No, la colpa non è degli altri…
::: SIAMO GEEK

Mostly adequate guide to FP (in javascript)
This is a book on the functional paradigm in general
::: DrBoolean

lol-face-funny-meme

Page 2
::: flaviadok

the mockups for the virtual desktops implementation under Budgie desktop
::: Google+

Try Periscope
::: periscope

PyData Seattle 2015 Scikit-Learn Tutorial
::: nbviewer

Eight years of blogging. Over one million visitors
10 volte OKp, Peteris rockz! :grin:
::: Peteris Krumins

kepler-452b

Wi-Fi libero, ma…
::: SIAMO GEEK

Google Voice transcriptions will soon actually make sense
::: Engadget

La BCE: Twitter può predire l’andamento della Borsa
::: ZEUS News

Trenta OS: Il tempo delle Pere 2
::: Nerd Slider

Twitter should not be used for reporting complex things
::: glipari

editors

Verification handbook
::: Luca De Biase

mbeddr: an Extensible C-based Programming Language and IDE for Embedded Systems
::: Lambda the Ultimate

Jusqu’au dernier souffle
::: CommitStrip

@KimKardashian great idea!
::: jack

David Mertz – Functional Programming in Python
::: O’Reilly

1a

The only remaining barrier to entry for Linux
::: TechRepublic

How to install Linux on a PC with Secure Boot enabled
::: PCWorld

What is Nuitka – The TL;DR …
Nuitka is a Python compiler
c’è nel Softare center di ‘buntu, in settimana… probabilmente …forse … :wink:
::: Nuitka

top-gnu

Iscriviti

Ricevi al tuo indirizzo email tutti i nuovi post del sito.

Unisciti agli altri 88 follower