Coconut – Istruzioni – 11

no-fun-allowed

Non so se si userà Coconut ma rockz😀 continuo da qui a copiare qui.

Istruzioni

Coconut supports significantly enhanced destructuring assignment, similar to Python’s tuple/list destructuring, but much more powerful. The syntax for Coconut’s destructuring assignment is

[match] <pattern> = <value> 

where <value> is any expression and <pattern> is defined by Coconut’s match statement. The match keyword at the beginning is optional, but is sometimes necessary to disambiguate destructuring assignment from normal assignment, which will always take precedence. Coconut’s destructuring assignment is equivalent to a match statement that follows the syntax:

match <pattern> in <value>:
    pass
else:
    err = MatchError(<error message>)
    err.pattern = "<pattern>"
    err.value = <value>
    raise err

If a destructuring assignment statement fails, then instead of continuing on as if a match block had failed, a MatchError object will be raised describing the failure.

c46

With Python can’t be done without a long series of checks in place of the destructuring assignment statement. See the compiled code for the Python syntax.

Decoratori
Unlike Python, which only supports a single variable or function call in a decorator, Coconut supports any expression.

L’esempio riportato non è completo e non ho trovato qualcosa di diverso da uno che seguirà prossimamente. Per cui riporto solo il codice senza eseguirlo.

Coconut:

@wrapper1 .. wrapper2 $(arg)
def func(x) = x**2

Python:

def wrapper(func):
    return wrapper1(wrapper2(arg, func))
@wrapper
def func(x):
    return x**2

Istruzioni else
Coconut supports the compound statements try, if, and match on the end of an else statement like any simple statement would be. This is most useful for mixing match and if statements together, but also allows for compound try statements.

Coconut:

try:
    unsafe_1()
except MyError:
    handle_1()
else: try:
    unsafe_2()
except MyError:
    handle_2()

Python:

try:
    unsafe_1()
except MyError:
    handle_1()
else:
    try:
        unsafe_2()
    except MyError:
        handle_2()

Istruzioni except
Python 3 requires that if multiple exceptions are to be caught, they must be placed inside of parentheses, so as to disallow Python 2’s use of a comma instead of as. Coconut allows commas in except statements to translate to catching multiple exceptions without the need for parentheses.

Coconut:

try:
    unsafe_func(arg)
except SyntaxError, ValueError as err:
    handle(err)

Python:

try:
    unsafe_func(arg)
except (SyntaxError, ValueError) as err:
    handle(err)


Lista di variabili

Coconut allows for the more elegant parenthetical continuation instead of the less elegant backslash continuation in import, del, global, and nonlocal statements.

c47

Codice passthrough
No, non so tradurlo (codice attraversante? orrendo!).
Coconut supports the ability to pass arbitrary code through the compiler without being touched, for compatibility with other variants of Python, such as Cython or Mython. Anything placed between \( and the corresponding close parenthesis will be passed through, as well as any line starting with \\, which will have the additional effect of allowing indentation under it.

Coconut:

\\cdef f(x):
    return x |> g

Python:

cdef f(x):
    return g(x)

:mrgreen:

Octave – istruzioni II – 42

Pi-Bond_002

Continuo, oggi qui.

L’istruzione while
In programming, a loop means a part of a program that is (or at least can be) executed two or more times in succession.
The while statement is the simplest looping statement in Octave. It repeatedly executes a statement as long as a condition is true. As with the condition in an if statement, the condition in a while statement is considered true if its value is nonzero, and false if its value is zero. If the value of the conditional expression in a while statement is a vector or a matrix, it is considered true only if it is non-empty and all of the elements are nonzero.
Octave’s while statement looks like this:

while (condition)
  body
endwhile

Here body is a statement or list of statements that we call the body of the loop, and condition is an expression that controls how long the loop keeps running.

The first thing the while statement does is test condition. If condition is true, it executes the statement body. After body has been executed, condition is tested again, and if it is still true, body is executed again. This process repeats until condition is no longer true. If condition is initially false, the body of the loop is never executed.
This example creates a variable fib that contains the first ten elements of the Fibonacci sequence.

o248

Here the body of the loop contains two three statements.

The loop works like this: first, the value of i is set to 3. Then, the while tests whether i is less than or equal to 10. This is the case when i equals 3, so the value of the i-th element of fib is set to the sum of the previous two values in the sequence. Then the i++ increments the value of i and the loop repeats. The loop terminates when i reaches 11.

A newline is not required between the condition and the body; but using one makes the program clearer unless the body is very simple.

Passo qui.

L’istruzione do-until
The do-until statement is similar to the while statement, except that it repeatedly executes a statement until a condition becomes true, and the test of the condition is at the end of the loop, so the body of the loop is always executed at least once. As with the condition in an if statement, the condition in a do-until statement is considered true if its value is nonzero, and false if its value is zero. If the value of the conditional expression in a do-until statement is a vector or a matrix, it is considered true only if it is non-empty and all of the elements are nonzero.
Octave’s do-until statement looks like this:

do
  body
until (condition)

Here body is a statement or list of statements that we call the body of the loop, and condition is an expression that controls how long the loop keeps running.

This example creates a variable fib that contains the first ten elements of the Fibonacci sequence.

o249

A newline is not required between the do keyword and the body; but using one makes the program clearer unless the body is very simple.

:mrgreen:

Octave – istruzioni I – 41

_9082

Proseguendo da qui oggi sono qui.


Istruzioni

Statements may be a simple constant expression or a complicated list of nested loops and conditional statements.
Control statements such as if, while, and so on control the flow of execution in Octave programs. All the control statements start with special keywords such as if and while, to distinguish them from simple expressions. Many control statements contain other statements; for example, the if statement contains another statement which may or may not be executed.
Each control statement has a corresponding end statement that marks the end of the control statement. For example, the keyword endif marks the end of an if statement, and endwhile marks the end of a while statement. You can use the keyword end anywhere a more specific end keyword is expected, but using the more specific keywords is preferred because if you use them, Octave is able to provide better diagnostics for mismatched or missing end tokens.
The list of statements contained between keywords like if or while and the corresponding end statement is called the body of a control statement.

Da qui si passa in dettaglio, un’istruzione alla volta, inizio da qui.

L’istruzione if
The if statement is Octave’s decision-making statement. There are three basic forms of an if statement. In its simplest form, it looks like this:

if (condition)
  then-body
endif

condition is an expression that controls what the rest of the statement will do. The then-body is executed only if condition is true.

The condition in an if statement is considered true if its value is nonzero, and false if its value is zero. If the value of the conditional expression in an if statement is a vector or a matrix, it is considered true only if it is non-empty and all of the elements are nonzero. The conceptually equivalent code when condition is a matrix is shown below.

if (matrix) ≡ if (all (matrix(:)))

The second form of an if statement looks like this:

if (condition)
  then-body
else
  else-body
endif

If condition is true, then-body is executed; otherwise, else-body is executed.
Here is an example:

o245

Il punto-virgola credo sia opzionale (correggerò se del caso).

The third and most general form of the if statement allows multiple decisions to be combined in a single statement. It looks like this:

if (condition)
  then-body
elseif (condition)
  elseif-body
else
  else-body
endif

Any number of elseif clauses may appear. Each condition is tested in turn, and if one is found to be true, its corresponding body is executed. If none of the conditions are true and the else clause is present, its body is executed. Only one else clause may appear, and it must be the last part of the statement.

In the following example, if the first condition is true (that is, the value of x is divisible by 2), then the first printf statement is executed. If it is false, then the second condition is tested, and if it is true (that is, the value of x is divisible by 3), then the second printf statement is executed. Otherwise, the third printf statement is performed.

o246

Note that the elseif keyword must not be spelled else if, as is allowed in Fortran. If it is, the space between the else and if will tell Octave to treat this as a new if statement within another if statement’s else clause. For example, if you write

if (c1)
  body-1
else if (c2)
  body-2
endif

Octave will expect additional input to complete the first if statement. If you are using Octave interactively, it will continue to prompt you for additional input. If Octave is reading this input from a file, it may complain about missing or mismatched end statements, or, if you have not used the more specific end statements (endif, endfor, etc.), it may simply produce incorrect results, without producing any warning messages.

It is much easier to see the error if we rewrite the statements above like this,

if (c1)
  body-1
else
  if (c2)
    body-2
  endif

using the indentation to show how Octave groups the statements.

Pronto a passare qui.

L’istruzione switch
It is very common to take different actions depending on the value of one variable. This is possible using the if statement in the following way

if (X == 1)
  do_something ();
elseif (X == 2)
  do_something_else ();
else
  do_something_completely_different ();
endif

This kind of code can however be very cumbersome to both write and maintain. To overcome this problem Octave supports the switch statement. Using this statement, the above example becomes

switch (X)
  case 1
    do_something ();
  case 2
    do_something_else ();
  otherwise
    do_something_completely_different ();
endswitch

This code makes the repetitive structure of the problem more explicit, making the code easier to read, and hence maintain. Also, if the variable X should change its name, only one line would need changing compared to one line per case when if statements are used.

The general form of the switch statement is

switch (expression)
  case label
    command_list
  case label
    command_list
  ...

  otherwise
    command_list
endswitch

where label can be any expression. However, duplicate label values are not detected, and only the command_list corresponding to the first match will be executed. For the switch statement to be meaningful at least one case label command_list clause must be present, while the otherwise command_list clause is optional.

If label is a cell array the corresponding command_list is executed if any of the elements of the cell array match expression. Example:

o247

As with all other specific end keywords, endswitch may be replaced by end, but you can get better diagnostics if you use the specific forms.

One advantage of using the switch statement compared to using if statements is that the labels can be strings. If an if statement is used it is not possible to write

if (X == "a string") # This is NOT valid

since a character-to-character comparison between X and the string will be made instead of evaluating if the strings are equal. This special-case is handled by the switch statement, and it is possible to write programs that look like this

switch (X)
  case "a string"
    do_something
  ...
endswitch

Non di stretto interesse (per me) ma c’è differenza rispetto al C (il case inclusivo e quindi il break), come raccontato qui.

:mrgreen:

L’ecosistema, Racket e un tutorial

Tin_Woodman
Un post che ho scritto e poi riscritto (stravolgendolo) in seguito a un colloquio con un ex-collega Mr.X che rockz😀
Inizialmente c’era solo la parte Racket –una delle mie passioni– ma quando Mr.X ha letto la bozza mi ha indotto a cambiare qualcosa, adesso vi conto.

Ci sono cose belle (sexy) ma spesso capita di doverne usare altre perché si usano quelle; cioè dove lavori tutti usano quelle.
Mr.X parla in questo caso di ecosistema. E per lui l’ecosistema e Windows, sempre più 10 ma con ancora qualche 7. E per i linguaggi quelli ammessi sono pochissimi, in funzione del task, si potrebbe parlare di sub-ecosistema. Per esempio per il Web solo HTML, CSS, JavaScript. JavaScript (come NodeJs) potrebbe essere usato anche da se. Altrimenti Java. O il VisualBasic. Assolutamente niente altro, meno che mai Lisp, linguaggi funzionali di moda solo nei blog ma non nella pratica. Ah! niente Python, a meno che usi solo quello, ma non per il Web.
E siccome tutti usano Windows niente Linux.

Ovviamente non sono d’accordo ma riporto questa opinione, credo anzi di approfondire l’argomento in futuro.
Altrettanto ovviamente continuerò peraltro a occuparmi anche delle cose che i piacciono, anche –e specie se– sono fuori della lista delle cose approvate. Per esempio Coconut, Haskell (forse, in futuro) e Racket. Ecco ero partito con Racket, questo che segue.

prl
Twitter vi fornisce consigli e suggerimenti che voi non tweeps non potete minimamente immaginare. Tutto sta nella scelta a chi followare e poi la magia segue, gratis😀

Comincio dal suggerimento più semplice (e fondamentale): il blog Inside PRL è da seguire. Obbligatorio (se volete, nèh!). Forse non tutti sanno che PRL sta per Programming Research Laboratory e fa parte del College of Computer and Information Science della Northeastern University, quella di Racket, nella città più sexy del Universo.

Nel blog –c’è altro ma devo ancora perlustrare– c’è questo Tutorial: Zero to Sixty in Racket. È per via di questo post che ho scoperto il blog, via questo cinguettio.
Uh! a proposito di @racketlang per me ha 17 Followers you know (su un totale di 220 (circa, numero soggetto a variazioni come il meteo).

OK, vengo al post di Ben Greenman: Racket is excellent for incrementally growing scripts into full-fledged programs. This post steps through the evolution of one small program and highlights the Racket tools that enable incremental advances… E continua, mica posso copiare tutto😳

Il compito che si pone è un indice KWIC (se non sapete cos’è un motivo in più per andarci, e protrete dire TIL KWIC), roba che secondo la letteratura richiede parecchio tempo (e poi ci sarebbe la Legge di Hofstadter che Ben colpevolmente non cita) ma c’è anche Yannis e –OK, 20 minuti dice Ben.

Siccome Ben è OK da per scontato che l’aspirante racketeer usi l’ambiente integrato, Dr Racket, manco sta a ricordarvelo. Io di solito uso la REPL, quella di una volta, mi sono pure fatto l’alias, alias rre='racket -il xrepl' ma solo perché sono vecchio (però non tanto vecchio da rientrare nella classe “non puoi insegnare un gioco nuovo a un cane vecchio”, nèh!), ma in questo cas è OK.

Nel codice trovate subito un’altra nerdata: λ invece di scrivere lambda. Il codice Unicode di λ è 03BB, per ottenerlo con Linux si sua Ctrl-Maiusc-U, compare una u sottolineata e si scrive il codice voluto. Con Windows chissà… (googlate). Ma potete benissimo scrivere lambda, come facevano i nostri vecchi (e me).

Poi basta seguire Ben, rockz!😀 Costruisce le funzioni che gli servono, spiegando quello che fa, visualizza il codice completo dello script, 79 righe compresi i commenti. Eseguendolo (tasto run) si ottiene test.txt ma è solo il primo passo.

Ben crea un submodule, lo esegue con raco, passa alla versione typed, aggiunge l’interfaccia per la command-line e testa il tutto. E continuerà –promette– con la documentazione e la creazione del package per condividerlo (shararlo).

I tempi? forse Ben è un po’ troppo ottimista c’è la legge di Hofstadter, io non sono così smart) ma OK: Racket & Ben rockzs😀
Io sono occupato con cose promesse da finire ma il blog l’ho RSSato subito.

:mrgreen:

Octave – valutazione – 40

hypatia

Oggi, continuando da qui, sono giunto qui.

Valutazione delle espressioni
Normally, you evaluate expressions simply by typing them at the Octave prompt, or by asking Octave to interpret commands that you have saved in a file.
Sometimes, you may find it necessary to evaluate an expression that has been computed and stored in a string, which is exactly what the eval function lets you do.

Built-in Function: eval (try)
Built-in Function: eval (try, catch)

If execution fails, evaluate the optional string catch.
The string try is evaluated in the current context, so any results remain available after eval returns.
The following example creates the variable A with the approximate value of 3.1416 in the current workspace.

o236

Notare i diversi modi di scrittura; l’ultima è più tradizionale, quella usata in altri linguaggi.

If an error occurs during the evaluation of try then the catch string is evaluated, as the following example shows:

o237

Programming Note: if you are only using eval as an error-capturing mechanism, rather than for the execution of arbitrary code strings, Consider using try/catch blocks or unwind_protect/unwind_protect_cleanup blocks instead. These techniques have higher performance and don’t introduce the security considerations that the evaluation of arbitrary code does.

Pronto a passare qui.

Chiamare una funzione per nome
The feval function allows you to call a function from a string containing its name. This is useful when writing a function that needs to call user-supplied functions. The feval function takes the name of the function to call as its first argument, and the remaining arguments are given to the function.

The following example is a simple-minded function using feval that finds the root of a user-supplied function of one variable using Newton’s method. No, non messa: non sono riuscito a farla funzionare e non ho trovato esempi simili googlando.

Built-in Function: feval (name, ...)
Evaluate the function named name.
Any arguments after the first are passed as inputs to the named function. For example, calls the function acos with the argument ‘-1

o238

The function feval can also be used with function handles of any sort (see Function Handles).
Historically, feval was the only way to call user-supplied functions in strings, but function handles are now preferred due to the cleaner syntax they offer. For example,

o239

are equivalent ways to call the function referred to by f. If it cannot be predicted beforehand whether f is a function handle, function name in a string, or inline function then feval can be used instead.

A similar function run exists for calling user script files, that are not necessarily on the user path

Command: run script
Function File: run ("script")

Run script in the current workspace.
Scripts which reside in directories specified in Octave’s load path, and which end with the extension “.m“, can be run simply by typing their name. For scripts not located on the load path, use run.
The file name script can be a bare, fully qualified, or relative filename and with or without a file extension. If no extension is specified, Octave will first search for a script with the “.m” extension before falling back to the script name without an extension.
Implementation Note: If script includes a path component, then run first changes the working directory to the directory where script is found. Next, the script is executed. Finally, run returns to the original working directory unless script has specifically changed directories.

Ecco lo script p-run:

# script p-run
# per i piemontesi: no nessun coniglio

n = 6 * 7
l = log(n)
r = exp(l)

eseguo:

o240

lo stesso script rinominato c_run.m viene eseguito in questo modo:

o241

Nota perso: ovvio che il nome non può contenere caratteri come -, +, *, …

Avanti, passo qui.

Valutazione in un diverso contesto
Before you evaluate an expression you need to substitute the values of the variables used in the expression. These are stored in the symbol table. Whenever the interpreter starts a new function it saves the current symbol table and creates a new one, initializing it with the list of function parameters and a couple of predefined variables such as nargin. Expressions inside the function use the new symbol table.
Sometimes you want to write a function so that when you call it, it modifies variables in your own context. This allows you to use a pass-by-name style of function, which is similar to using a pointer in programming languages such as C.

Consider how you might write save and load as m-files. For example:

o242

With evalin, you could write save as follows:

o243

Here, ‘caller’ is the create_data function and name1 is the string "x", which evaluates simply as the value of x.
You later want to load the values back from mydata in a different context:

function process_data
  load mydata
  ... do work ...
endfunction

With assignin, you could write load as follows:

o244

Here, ‘caller’ is the process_data function.
You can set and use variables at the command prompt using the context ‘base’ rather than ‘caller’.
These functions are rarely used in practice. One example is the fail (‘code’, ‘pattern’) function which evaluates ‘code’ in the caller’s context and checks that the error message it produces matches the given pattern. Other examples such as save and load are written in C++ where all Octave variables are in the ‘caller’ context and evalin is not needed.

Alquanto misterioso, occorrerebbe provare in un caso particolare ma pare si usi raramente, praticamente mai.

Built-in Function: evalin (context, try)
Built-in Function: evalin (context, try, catch)

Like eval, except that the expressions are evaluated in the context context, which may be either "caller" or "base".

Built-in Function: assignin (context, varname, value)
Assign value to varname in context context, which may be either "base" or "caller".

:mrgreen:

Visto nel Web – 249

Le ferie stanno finendo; riparte il campionato di calcio per cui devo defolloware twittatori compulsivi (pro- e contro- il Metodo); ripartono –prossimamente– anche i nerdsprogrammers; intanto ecco cosa ho visto nel Web.

CqLlw6mWcAAf2Y8

Obsolesced: rise and fall of the Gopher protocol
seguire il link nel post
#:storia
::: OS news

the bad guys are not so smart (fortunately for us)
#:sicurezza, spionaggio
::: glipari

Voting Machines Can Be Easily Compromised, Symantec Demonstrates
#:sicurezza, spionaggio
::: Slashdot

Il machine learning e i suoi fratelli: un percorso tra python, la libreria scikit-learn e diversi modelli di classificazione
dal Carnevale della Matematica n. 100
#:linguaggi di programmazione
::: Math is in the air

Why Facebook Is Really Blocking the Ad Blockers
un motivo in più per non usare FB
#:spam
::: The New Yorker

13932956_904059803055857_4894999812372504515_n

Can We Avoid Government Surveillance By Leaving The Grid?
#:sicurezza, spionaggio
::: Slashdot

Billionaire Launches Free Code College in California
#:free open source software
::: Slashdot

Go 1.7 has been released!
#:linguaggi di programmazione
::: golang

Il ‘padre del web’ Tim Berners Lee vuole restituire Internet ai cittadini
#:Web, Internet
::: valigiablu

The hack of an NSA malware staging server is not unprecedented, but the publication of the take is. Here’s what you need to know: (1/x)
#:sicurezza, spionaggio
::: Snowden

13934882_10210411446588264_8035874917780759505_n

China Launches World’s First Quantum Communications Satellite
da verificare, nèh!
#:sicurezza, spionaggio
::: Slashdot

Twitter per la scienza #icanhazpdf
::: iamscicomm

Why Cory Doctorow Thinks Apple’s Disappearing Headphone Jack Should Scare You
#:copyright
::: Fast Company

Internet Explorer came out #otd in 1995 & reigned supreme pre-Chrome
#:Web, Internet
::: MIT_CSAIL

1 to 1 Billion: Eight Exponential Entrepreneurial Stories
#:ditte
::: Computer History Museum

CqM3M7dUAAAqltP

Windows vs. Unix: Those pesky line terminators
questa è una delle cose che continuo a dimenticare da 30 anni; lo ricordo perfettamente
#:tools, componenti software
::: ComputerWorld

The Document Foundation & FSFE strengthen their relationship
#:free open source software
::: tdforg

Quand tu as besoin d’une info pendant l’été
#:umorismo
::: CommitStrip

Confirmed: hacking tool leak came from “omnipotent” NSA-tied group
#:sicurezza, spionaggio
::: Ars Technica

CEO Tim Cook Decides Apple Doesn’t Have to Pay Corporate Tax Rate Because It’s “Unfair”
bello poter are come Apple😉
#:ditte
::: The Intercept

13912392_996359827148117_7795579242630715053_n

From Now On You’ll Be Able To Access NASA Research For Free
#:Web, Internet #:free open source software
::: Slashdot

Microsoft Says Upcoming Project Scorpio Might Be the Last Console Generation
#:hardware #:innovazioni, futuro
::: Slashdot

Apple steps up environmental efforts in China
#:ditte
::: Macworld

I wrote this! Making documentation easy with Read the Docs
#:free open source software #:manuali, how to
::: FunnelFiasco

Announcing Rust 1.11
#:linguaggi di programmazione
::: The Rust Programming Language

13934760_665304710291595_186973354821035046_n

How bad is the Windows command line really?
#:sistemi operativi
::: Grab the Blaster ::: Grab the Blaster

I wrote a short blog post about programming languages, abstraction, and tradeoffs
troppo difficile per commentarlo; concordo in parte –ovviamente da niubbo (beginner dice lei)😉
#:linguaggi di programmazione
::: lexi_lambda

Happy Learn Haskell Tutorial Volume 1
lodevole iniziativa😀 lo metto nella pagina dei manuali
#:programmazione funzionale
::: Leanpub

Happy Learn Haskell Tutorial
#:programmazione funzionale
::: Happy Learn Haskell Tutorial

Microsoft Wants To Pay You To Use Its Windows 10 Browser Edge
mahhhh…😳
#:ditte
::: Slashdot

CqJ4vPdWYAAVlAz

The Link Tax is Running Out of Fuel: You Can Stop It Here
una pazzia della Comunità Europea, peggiore di quella sulla segnalazione dei cookies
#:copyright
::: OpenMedia

Google Will Kill Chrome Apps For Windows, Mac, and Linux In Early 2018
#:Web, Internet #:ditte
::: Slashdot ::: Grab the Blaster

Oracle Is Funding a New Anti-Google Group
mi ricorda tanto SCO
#:ditte
::: Slashdot

Page maison de Simon Plouffe
il sito è in inglese, contiene infinite risorse principalmene matematiche ma che possono servire per la programmaione; devo mica dirvi chi è Simon, vero?
#:manuali, how to
::: Simon Plouffe ::: Wikipedia

Fedora 25 To Run Wayland By Default Instead Of X.Org Server
#:sistemi operativi
::: Slashdot

Computer Science Professor Mocks The NSA’s Buggy Code
mah… sarà davvero così o *gomblotto*—–😳
#:sicurezza, spionaggio
::: Slashdot

kiss

SICP – cap. 1 – formulare astrazioni con procedure di ordine superiore – esercizi – 37

Cg5

Copiando qui proseguo da qui.

Exercise 1.30: The sum procedure above generates a linear recursion. The procedure can be rewritten so that the sum is performed iteratively. Show how to do this by filling in the missing expressions in the following definition:

(define (sum term a next b)
  (define (iter a result)
    (if 
        (iter )))
  (iter ))

Si tratta di mettere a frutto quanto visto in precedenza, verifica se siete stati attenti. Uno che è sempre attento è Bill the Lizard, un modello (lo propongo come capoclasse e incaricato di cancellare la lavagna (si usa ancora, vero?)). E spiega bene-bene il tutto, qui.

Il risultato è:

(define (sum term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a) (+ (term a) result))))
  (iter a 0))

Sostituisco questa definizione alla vecchia usata per l’esercizio precedente ottenendo:

(define (cube x) (* x x x))

(define (sum term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a) (+ (term a) result))))
  (iter a 0))

(define (integral f a b dx)
  (define (add-dx x) (+ x dx))
  (* (sum f (+ a (/ dx 2.0)) add-dx b)
     dx))
     
(define (simpson f a b n)
  (define h (/ (- b a) n))
  (define (inc x) (+ x 1))
  (define (y k)
    (f (+ a (* k h))))
  (define (term k)
    (* (cond ((odd? k) 4)
             ((or (= k 0) (= k n)) 1)
             ((even? k) 2))
       (y k)))
  (/ (* h (sum term 0 inc n)) 3))

s79

Molto sintetici (e inutili) Ken Dyck, S-sol (che lo applica a un calcolo differente) e Spaceman Aki.

:mrgreen:

Octave – espressioni VII – 39

1352

Copio qui, continuando da qui.

Operatori d’incremento

Increment operators increase or decrease the value of a variable by 1. The operator to increment a variable is written as ‘++’. It may be used to increment a variable either before or after taking its value.
For example, to pre-increment the variable x, you would write ++x. This would add one to x and then return the new value of x as the result of the expression. It is exactly the same as the expression x = x + 1.
To post-increment a variable x, you would write x++. This adds one to the variable x, but returns the value that x had prior to incrementing it. For example, if x is equal to 2, the result of the expression x++ is 2, and the new value of x is 3.
For matrix and vector arguments, the increment and decrement operators work on each element of the operand.

Here is a list of all the increment and decrement expressions.

++x
This expression increments the variable x. The value of the expression is the new value of x. It is equivalent to the expression x = x + 1.

--x
This expression decrements the variable x. The value of the expression is the new value of x. It is equivalent to the expression x = x - 1.

x++
This expression causes the variable x to be incremented. The value of the expression is the old value of x.

x--
This expression causes the variable x to be decremented. The value of the expression is the old value of x.

😀 proprio come nel C (e derivati e successori).

Avanti, sono qui.

Precedenza tra operatori
Operator precedence determines how operators are grouped, when different operators appear close by in one expression. For example, ‘*’ has higher precedence than ‘+’. Thus, the expression a + b * c means to multiply b and c, and then add a to the product (i.e., a + (b * c)).
You can overrule the precedence of the operators by using parentheses. You can think of the precedence rules as saying where the parentheses are assumed if you do not write parentheses yourself. In fact, it is wise to use parentheses whenever you have an unusual combination of operators, because other people who read the program may not remember what the precedence is in this case. You might forget as well, and then you too could make a mistake. Explicit parentheses will help prevent any such mistake.
When operators of equal precedence are used together, the leftmost operator groups first, except for the assignment operators, which group in the opposite order. Thus, the expression a - b + c groups as (a - b) + c, but the expression a = b = c groups as a = (b = c).
The precedence of prefix unary operators is important when another operator follows the operand. For example, -x^2 means -(x^2), because ‘-’ has lower precedence than ‘^’.
Here is a table of the operators in Octave, in order of decreasing precedence. Unless noted, all operators group left to right.

function call and array indexing, cell array indexing, and structure element indexing
()’ ‘{}’ ‘.

postfix increment, and postfix decrement
++’ ‘--
These operators group right to left.

transpose and exponentiation
'’ ‘.'’ ‘^’ ‘**’ ‘.^’ ‘.**

unary plus, unary minus, prefix increment, prefix decrement, and logical “not
+’ ‘-’ ‘++’ ‘--’ ‘~’ ‘!

multiply and divide
*’ ‘/’ ‘\’ ‘.\’ ‘.*’ ‘./

add, subtract
+’ ‘-

colon
:

relational
<’ ‘<=’ ‘==’ ‘>=’ ‘>’ ‘!=’ ‘~=

element-wise “and
&

element-wise “or
|

logical “and
&&

logical “or
||

assignment
=’ ‘+=’ ‘-=’ ‘*=’ ‘/=’ ‘\=’ ‘^=’ ‘.*=’ ‘./=’ ‘.\=’ ‘.^=’ ‘|=’ ‘&=
These operators group right to left.

:mrgreen:

Coconut – Notazione di funzione – 10

74

Coconut mi piace, tanto che continuando da qui oggi copio qui.

Operatori di funzione
Coconut uses a simple operator function short-hand: surround an operator with parentheses to retrieve its function. Similarly to iterator comprehensions, if the operator function is the only argument to a function, the parentheses of the function call can also serve as the parentheses for the operator function.

c46

A very common thing to do in functional programming is to make use of function versions of built-in operators: currying them, composing them, and piping them. To make this easy, Coconut provides a short-hand syntax to access operator functions.

La lista completa

(|>)     => # pipe forward
(|*>)    => # multi-arg pipe forward
(<|)     => # pipe backward
(<*|)    => # multi-arg pipe backward
(..)     => # function composition
(.)      => (getattr)
(::)     => (itertools.chain) # will not evaluate its arguments lazily
($)      => (functools.partial)
(+)      => (operator.__add__)
(-)      => # 1 arg: operator.__neg__, 2 args: operator.__sub__
(*)      => (operator.__mul__)
(**)     => (operator.__pow__)
(/)      => (operator.__truediv__)
(//)     => (operator.__floordiv__)
(%)      => (operator.__mod__)
(&)      => (operator.__and__)
(^)      => (operator.__xor__)
(|)      => (operator.__or__)
(<<)     => (operator.__lshift__)
(>>)     => (operator.__rshift__)
(<)      => (operator.__lt__)
(>)      => (operator.__gt__)
(==)     => (operator.__eq__)
(<=)     => (operator.__le__)
(>=)     => (operator.__ge__)
(!=)     => (operator.__ne__)
(~)      => (operator.__inv__)
(@)      => (operator.__matmul__)
(not)    => (operator.__not__)
(and)    => # boolean and
(or)     => # boolean or
(is)     => (operator.is_)
(in)     => (operator.__contains__)

c47

 

Creare scorciatoie di funzione
Coconut allows for shorthand in-line function definition, where the body of the function is assigned directly to the function call. The syntax for shorthand function definition is

def <name>(<args>) = <expr>

where <name> is the name of the function, <args> are the functions arguments, and <expr> evaluates the value that the function should return.

Note: Shorthand function definition can be combined with infix and pattern-matching function definition.

Coconut’s shorthand function definition is as easy to write as assignment to a lambda, but will appear named in tracebacks, as it compiles to normal Python function definition.

c48

Finzioni infisse
Coconut allows for infix function calling, where a function is surrounded by backticks and then can have arguments placed in front of or behind it. Backtick calling has a precedence in-between chaining and piping.

Coconut also supports infix function definition to make defining functions that are intended for infix usage simpler. The syntax for infix function definition is

def <arg> `<name>` <arg>:
    <body

where <name> is the name of the function, the <arg>s are the function arguments, and <body> is the body of the function. If an <arg> includes a default, the <arg> must be surrounded in parentheses.

Note: Infix function definition can be combined with shorthand and pattern-matching function definition.

A common idiom in functional programming is to write functions that are intended to behave somewhat like operators, and to call and define them by placing them between their arguments. Coconut’s infix syntax makes this possible.

c49

Con la tastiera italiana ` si ottiene con AltGr+' (nota per me che la memoria…)😉

Pattern-matching di funzioni
Coconut supports pattern-matching / destructuring assignment syntax inside of function definition. The syntax for pattern-matching function definition is

[match] def <name>(<pattern>, <pattern>, ... [if <cond>]):
    <body>

where <name> is the name of the function, <cond> is an optional additional check, <body> is the body of the function, and <pattern> is defined by Coconut’s match statement. The match keyword at the beginning is optional, but is sometimes necessary to disambiguate pattern-matching function definition from normal function definition, which will always take precedence. Coconut’s pattern-matching function definition is equivalent to a match statement that looks like:

def <name>(*args):
    match (<pattern>, <pattern>, ...) in args:
        <body>
    else:
        err = MatchError(<error message>)
        err.pattern = "def <name>(<pattern>, <pattern>, ...):"
        err.value = args
        raise err

If pattern-matching function definition fails, it will raise a [MatchError]((#matcherror) object just like destructuring assignment.

Note: Pattern-matching function definition can be combined with shorthand and infix function definition.

c50

In Python can’t be done without a long series of checks at the top of the function. See the compiled code for the Python syntax.

:mrgreen:

 

with, un complemento a REPL

lambda
Appena finito di postare una cosa sulla REPL ecco un tweet che mi constringe a fermare tutto quello che dovrei fare e compilare un post di aggiornamento && completamento al precedente.

Intanto –prima di subito– bravo Michael!😀 (come si vedrà a breve).
Tutto nasce da un tweet –come farei senza Tswitter?– questo: Awesome little script from @_mchav – seems great for building up complex commands with ‘+’🙂

C’è l’indirizzo Twitter dell’autore, ci vado (sapete sono addict a λ) e scopro che è nuovo di pakka, chissà…

mchav

Uh! solo 2 followers, no ‘spetta 3: ci sono anch’io (me).
Il Git conferma l’asserzione di TomNomNom.

il README.md recita

# with
Program prefixing for continuous workflow using a single tool.

### Usage

`with <program>`

Starts an interactive shell with where every command is prefixed using `<program>`.

Da provare prima di subito; è uno script Bash, non lo pubblico, c’è di là. Funziona, ecco:

mc0
C’è l’autocompletamento del path (quello con Tab), c’è l’editing della command-line (quello delle frecce). Leggendo lo script mi viene da dire “oh! basta là!”.

mc1
Insomma faccio un paio di piccole personalizzazioni (p.es. quando si esce deve andare a capo) e lo abilito con chmod.
E terrò d’occhio @_mchav, merita tanti followers😀 anzi –promesso, giurin-giuretta, parola di ex-Giovane Marmotta– un #FF dopodomani (lo farei subito ma non è stagione).

:mrgreen:

Iscriviti

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

Segui assieme ad altri 95 follower