Author Archives: juhan

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

gg

SICP meriterebbe più attenzione ma in questo periodo sono impegnato per una scadenza (incombe sempre più incombente :oops:). Continuo, ecco un altro esercizio, qui.

Exercise 1.31:
a.  The sum procedure is only the simplest of a vast number of similar abstractions that can be captured as higher-order procedures. Write an analogous procedure called product that returns the product of the values of a function at points over a given range. Show how to define factorial in terms of product. Also use product to compute approximations to using the formula discovered by the seventeenth-century English mathematician John Wallis:

s80

b.  If your product procedure generates a recursive process, write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.

Siccome Bill the Lizard usa la formula di Wallis (OT?) conviene seguire qualcun’altro dei lispers, ecco s-sicp, (Community-Scheme-Wiki).

Parte a: ricorsiva:

(define (product term a next b) 
  (if (> a b) 1 
  (* (term a) (product term (next a) next b)))) 
(define (identity x) x) 
(define (next x) (+ x 1)) 
(define (pi-term n) 
  (if (even? n) 
    (/ (+ n 2) (+ n 1)) 
    (/ (+ n 1) (+ n 2))))

s81

Ho eliminato la definizione di factorial, non necessaria per il calcolo di pi, ma bellissima in termini di product, identity e next:

(define (factorial n) 
  (product identity 1 next n))

Parte b: iterativa:

(define (identity x) x) 
(define (next x) (+ x 1)) 
(define (pi-term n) 
  (if (even? n) 
    (/ (+ n 2) (+ n 1)) 
    (/ (+ n 1) (+ n 2))))
(define (product term a next b) 
  (define (iter a res) 
    (if (> a b) res 
      (iter (next a) (* (term a) res)))) 
    (iter a 1))

s82

Sul post sono presenti altre due varianti, s-sicp rockzs😀

Buona anche la soluzione di Ken Dycke, al solito senza spiegazioni.

:mrgreen:

Visto nel Web – 250

L’estate sta finendo (cit.) ma la telenovela continua; ecco cosa ho visto nel Web.

CqsNBD2VYAAgnRu

Facebook AI Research is open-sourcing fastText
#:programming, codice, snippet
::: marcelsalathe

Share it here,FB, text your friends. Call your mom. Let’s get people to understand #TPP. #NoTPP
#:Web, Internet
::: canativeobt

Per l’anniversario Windows 10 fa la festa. Al disco
#:sistemi operativi
::: Tech Economy

Il mio iMac è più bravo di me nel riconoscere i miei figli
#:innovazioni, futuro
::: L’estinto

Genitori e figli alle prese con il web, fra qualche rischio e tantissime opportunità
#:Web, Internet
::: giowile

Stay positive

A New Way to Debug Our Election Systems
a me sembra un’ottima idea😀
#:sicurezza, spionaggio
::: Knowing and Doing

wc in x64 assembly
uh! anche l’assembler 64 bits
#:programming, codice, snippet
::: Eli Bendersky

Come di consueto, classifiche olimpiche
proooof Zar rcokz!
#:programming, codice, snippet
::: Gli studenti di oggi ::: Gli studenti di oggi

Not a #Git fan? Here’s “Gitless,” a CSAIL student’s solution
#:tools, componenti software
::: MIT_CSAIL

Facebook Knows Your Political Preferences
#:Web, Internet
::: Slashdot

CquX02iWcAE0KK-

20% of Scientific Papers On Genes Contain Conversion Errors Caused By Excel, Says Report
#:umorismo
::: Slashdot

I didn’t know that Racket supports limited infix, a la Haskell:
uh! da indagare
#:lisp e derivati
::: wallingf

Hask
Hask is a pure-Python, zero-dependencies library that mimics most of the core language tools from Haskell
#:linguaggi di programmazione
::: billpmurphy

Mochi
Mochi is a dynamically typed programming language for functional programming and actor-style programming
#:linguaggi di programmazione
::: i2y

I’ve published a longer excerpt from Beautiful Racket, including two new tutorials
#:lisp e derivati
::: mbutterick

CqzarV9W8AAAI7f

Georges Dupéron wrote a type expanders library for typed/racket
#:lisp e derivati
::: racketlang

Dinosaur and Lisp
segnalato da –ahemmm– vediamo :(){ :|:& };: (Gilles, Luke, aqquello)😀
#:lisp e derivati
::: Vito Van

Why are there so many programming languages?
#:linguaggi di programmazione
::: ThePracticalDev

NEW ISSUE! Get started with #RaspberryPi in the latest issue of the official magazine
#:media
::: TheMagP1

MIT Scientists Develop New Wi-Fi That’s 330% Faster
#:Web, Internet
::: Slashdot

Cq2wWLJXYAQO4Qv

Des spécifications très complètes et très précises
#:programming, codice, snippet
::: CommitStrip

Faster dictionary decoding with SIMD instructions
#:programming, codice, snippet
::: Daniel Lemire

Functional Programming by Example
#:programmazione funzionale
::: Caio Rodrigues

A Unix Utility You Should Know About: lsof
#:tools, componenti software
::: Peteris Krumins

Why Software Patents are Bad, Period
#:copyright
::: MOLLY ROCKET

Cq2wcAiXYAA6cS4

Focus: Uno sguardo ad aziende e servizi che si basano su Linux
#:sistemi operativi
::: lffl

Un po’ di numeri
#:sistemi operativi
::: rewasp1973

Leaked European copyright proposal would cause massive changes to Internet platforms and news sites as we know them
#:copyright
::: EFF

Ntfy: A utility for sending notifications
#:tools, componenti software
::: f_126_ck

ezgif-1284545325

Octave – funzioni e scripts I – 45

gravitationally_lensed_galaxy_1154x866

Capitolo nuovo, molto meno noioso (spero), qui, continuando da qui.

Funzioni e scripts
Complicated Octave programs can often be simplified by defining functions. Functions can be defined directly on the command line during interactive Octave sessions, or in external files, and can be called just like built-in functions.

Avanti, qui.

Introduzione a funzioni e script files
There are seven different things covered in this section:

  • Typing in a function at the command prompt;
  • Storing a group of commands in a file — called a script file;
  • Storing a function in a file—called a function file;
  • Subfunctions in function files;
  • Multiple functions in one script file;
  • Private functions;
  • Nested functions.

Both function files and script files end with an extension of .m, for MATLAB compatibility. If you want more than one independent functions in a file, it must be a script file (see Script Files), and to use these functions you must execute the script file before you can use the functions that are in the script file.

Avanti, qui.

Definire funzioni
In its simplest form, the definition of a function named name looks like this:

function name
  body
endfunction

A valid function name is like a valid variable name: a sequence of letters, digits and underscores, not starting with a digit. Functions share the same pool of names as variables.
The function body consists of Octave statements. It is the most important part of the definition, because it says what the function should actually do.
For example, here is a function that, when executed, print “ciao!” on your terminal:

function hello
  printf ("ciao!\n");
endfunction

o262

The printf statement (see Input and Output) simply tells Octave to print the string “ciao!\n“. The special character ‘\n’ stands for the newline character (ASCII 10). See Strings.
Once this function is defined, you can ask Octave to evaluate it by typing the name of the function.

Normally, you will want to pass some information to the functions you define. The syntax for passing parameters to a function in Octave is

function name (arg-list)
  body
endfunction

where arg-list is a comma-separated list of the function’s arguments. When the function is called, the argument names are used to hold the argument values given in the call. The list of arguments may be empty, in which case this form is equivalent to the one shown above.

To print a name along with the greeting, you might modify hello to look like this:

function hello_n(name)
  printf ("ciao %s!\n", name);
endfunction

o263

In most cases, you will also want to get some information back from the functions you define. Here is the syntax for writing a function that returns a single value:

function ret-var = name (arg-list)
  body
endfunction

The symbol ret-var is the name of the variable that will hold the value to be returned by the function. This variable must be defined before the end of the function body in order for the function to return a value.
Variables used in the body of a function are local to the function. Variables named in arg-list and ret-var are also local to the function. See Global Variables, for information about how to access global variables inside a function.

Notare la sintassi diversa dal solito, p.es C e Python.

For example, here is a function that computes the average of the elements of a vector:

function retval = avg (v)
  retval = sum (v) / length (v);
endfunction

o264

If we had written avg like this instead,

function retval = avg (v)
  if (isvector (v))
    retval = sum (v) / length (v);
  endif
endfunction

and then called the function with a matrix instead of a vector as the argument, Octave would have printed an error message like this:

error: value on right hand side of assignment is undefined

because the body of the if statement was never executed, and retval was never defined. To prevent obscure errors like this, it is a good idea to always make sure that the return variables will always have values, and to produce meaningful error messages when problems are encountered. For example, avg could have been written like this:

function retval = avg (v)
  retval = 0;
  if (isvector (v))
    retval = sum (v) / length (v);
  else
    error ("avg: expecting vector argument");
  endif
endfunction

There is still one additional problem with this function. What if it is called without an argument? Without additional error checking, Octave will probably print an error message that won’t really help you track down the source of the error. To allow you to catch errors like this, Octave provides each function with an automatic variable called nargin. Each time a function is called, nargin is automatically initialized to the number of arguments that have actually been passed to the function. For example, we might rewrite the avg function like this:

function retval = avg (v)
  retval = 0;
  if (nargin != 1)
    usage ("avg (vector)");
  endif
  if (isvector (v))
    retval = sum (v) / length (v);
  else
    error ("avg: expecting vector argument");
  endif
endfunction

Although Octave does not automatically report an error if you call a function with more arguments than expected, doing so probably indicates that something is wrong. Octave also does not automatically report an error if a function is called with too few arguments, but any attempt to use a variable that has not been given a value will result in an error. To avoid such problems and to provide useful messages, we check for both possibilities and issue our own error message.

Built-in Function: nargin ()
Built-in Function: nargin (fcn)

Report the number of input arguments to a function.
Called from within a function, return the number of arguments passed to the function. At the top level, return the number of command line arguments passed to Octave.
If called with the optional argument fcn —a function name or handle— return the declared number of arguments that the function can accept.

If the last argument to fcn is varargin the returned value is negative. For example

o265

Programming Note: nargin does not work on built-in functions.

Function File: inputname (n)
Return the name of the n-th argument to the calling function.
If the argument is not a simple variable name, return an empty string. inputname may only be used within a function body, not at the command line.

o266

Uhmmmm… la funzione ritorna comunque un valore (l’ultimo?), verifico:

o267

quasi-panico😳
In pratica –se ho capito bene– inputname può essere utile solo all’interno della funzione;dubbio sulla sua utilità qui.

Built-in Function: val = silent_functions ()
Built-in Function: old_val = silent_functions (new_val)
Built-in Function: silent_functions (new_val, "local")

Query or set the internal variable that controls whether internal output from a function is suppressed.
If this option is disabled, Octave will display the results produced by evaluating expressions within a function body that are not terminated with a semicolon.
When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

o268

Note: ho dimenticato le parentesi dopo il nome della chiamata a funzione e questa ha funzionato normalmente (sono evidentemente opzionali); silent_functions() può servre per il debug. Chiarito così anche il punto-virgola nelle funzioni.

Nel post ci sono cose scontate, usuali e quindi probabilmente già note mischiate a altre caratteristiche di Octave (e Matlab), da acquisire perché atipiche diverse dagli altri linguaggi😳

:mrgreen:

Coconut – built-ins – 12

Coj9

Continuo da qui, oggi su built-ins che semplificano il codice, qui.

addpattern
Takes one argument that is a pattern-matching function, and returns a decorator that adds the patterns in the existing function to the new function being decorated, where the existing patterns are checked first, then the new. Equivalent to:

def addpattern(base_func):
    """Decorator to add a new case to 
       a pattern-matching function, 
       where the new case is checked last."""
    
    def pattern_adder(func):
        def add_pattern_func(*args, **kwargs):
            try:
                return base_func(*args, **kwargs)
            except MatchError:
                return func(*args, **kwargs)
        return add_pattern_func
    return pattern_adder

c48

cosa che con Python … ahemmmm, già😉

prepattern
Takes one argument that is a pattern-matching function, and returns a decorator that adds the patterns in the existing function to the new function being decorated, where the new patterns are checked first, then the existing. Equivalent to:

def prepattern(base_func):
    """Decorator to add a new case to
       a pattern-matching function, 
       where the new case is checked first."""
    def pattern_prepender(func):
        def pre_pattern_func(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except MatchError:
                return base_func(*args, **kwargs)
        return pre_pattern_func
    return pattern_prepender

c49

con Python –come già detto.

reduce
Coconut re-introduces Python 2’s reduce built-in, using the functools.reduce version.
Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce((x, y) -> x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.

c50

takewhile
Coconut provides itertools.takewhile as a built-in under the name takewhile.
takewhile(predicate, iterable)
Make an iterator that returns elements from the iterable as long as the predicate is true. Equivalent to:

def takewhile(predicate, iterable):
    # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
    for x in iterable:
        if predicate(x):
            yield x
        else:
            break

L’esempio proposto mi da errore, forse dovuto alla versione😦

Coconut:
negatives = takewhile(numiter, (x) -> x<0)

Python:
import itertools
negatives = itertools.takewhile(numiter, lambda x: x<0)


dropwhile
Coconut provides itertools.dropwhile as a built-in under the name dropwhile.

dropwhile(predicate, iterable)
Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element. Note: the iterator does not produce any output until the predicate first becomes false, so it may have a lengthy start-up time. Equivalent to:

def dropwhile(predicate, iterable):
    # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
    iterable = iter(iterable)
    for x in iterable:
        if not predicate(x):
            yield x
            break
    for x in iterable:
        yield x

Come per il caso precedente ottengo un errore.

Coconut:
positives = dropwhile(numiter, (x) -> x<0)

Python:
import itertools
positives = itertools.dropwhile(numiter, lambda x: x<0)

tee
Coconut provides itertools.tee as a built-in under the name tee.
tee(iterable, n=2)
Return n independent iterators from a single iterable. Equivalent to:

def tee(iterable, n=2):
    it = iter(iterable)
    deques = [collections.deque() for i in range(n)]
    def gen(mydeque):
        while True:
            if not mydeque:             # when the local deque is empty
                newval = next(it)       # fetch a new value and
                for d in deques:        # load it to all the deques
                    d.append(newval)
            yield mydeque.popleft()
    return tuple(gen(d) for d in deques)

Once tee() has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed.

This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().

c51

consume
Coconut provides the consume function to efficiently exhaust an iterator and thus perform any lazy evaluation contained within it. consume takes one optional argument, keep_last, that defaults to 0 and specifies how many, if any, items from the end to return as an iterable (None will keep all elements). Equivalent to:

def consume(iterable, keep_last=0):
    """Fully exhaust iterable and return the last keep_last elements."""
    return collections.deque(iterable, maxlen=keep_last) 
                                    # fastest way to exhaust an iterator

In the process of lazily applying operations to iterators, eventually a point is reached where evaluation of the iterator is necessary. To do this efficiently, Coconut provides the consume function, which will fully exhaust the iterator given to it.

c52

count
Coconut provides a modified version of itertools.count that supports in, normal slicing, optimized iterator slicing, count and index sequence methods, repr, and _start and _step attributes as a built-in under the name count.
count(start=0, step=1)
Make an iterator that returns evenly spaced values starting with number start. Often used as an argument to map() to generate consecutive data points. Also, used with zip() to add sequence numbers. Roughly equivalent to:

def count(start=0, step=1):
    # count(10) --> 10 11 12 13 14 ...
    # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
    n = start
    while True:
        yield n
        n += step

c53

Verifica:

c53-1

In Python can’t be done quickly without Coconut’s iterator slicing, which requires many complicated pieces. The necessary definitions in Python can be found in the Coconut header.

map and zip
Coconut’s map and zip objects are enhanced versions of their Python equivalents that support normal slicing, optimized iterator slicing (through __coconut_is_lazy__), reversed, len, repr, and have added attributes which subclasses can make use of to get at the original arguments to the object (map supports _func and _iters attributes and zip supports the _iters attribute).

c54

In Python can’t be done without defining a custom map type.

datamaker
Coconut provides the datamaker function to allow direct access to the base constructor of data types created with the Coconut data statement. This is particularly useful when writing alternative constructors for data types by overwriting __new__. Equivalent to:

def datamaker(data_type):
    """Returns base data constructor of data_type."""
    return super(data_type, data_type).__new__$(data_type)

Coconut:

data trilen(h):
def __new__(cls, a, b):
return (a**2 + b**2)**0.5 |> datamaker(cls)

Python:

import collections
class trilen(collections.namedtuple("trilen", "h")):
    __slots__ = ()
    def __new__(cls, a, b):
        return super(cls, cls).__new__(cls, (a**2 + b**2)**0.5)


recursive

Coconut provides a recursive decorator to perform tail recursion optimization on a function written in a tail-recursive style, where it directly returns all calls to itself. Do not use this decorator on a function not written in a tail-recursive style or the function will likely break.

c55

La REPL visualizza male la riga “raise TypeError("the argument must be an integer >= 0")“.

In Python can’t be done without a long decorator definition. The full definition of the decorator in Python can be found in the Coconut header.

parallel_map
Coconut provides a parallel version of map under the name parallel_map. parallel_map makes use of multiple processes, and is therefore often much faster than map. Use of parallel_map requires concurrent.futures, which exits in the Python 3 standard library, but under Python 2 will require python -m pip install futures to function.
Because parallel_map uses multiple processes for its execution, it is necessary that all of its arguments be pickleable. Only objects defined at the module level, and not lambdas, objects defined inside of a function, or objects defined inside of the interpreter, are pickleable. Furthermore, on Windows, it is necessary that all calls to parallel_map occur inside of an if __name__ == "__main__" guard.

parallel_map(_func, *iterables_)

Equivalent to map(func, *iterables) except func is executed asynchronously and several calls to func may be made concurrently. If a call raises an exception, then that exception will be raised when its value is retrieved from the iterator.

c56

e

c57

MatchError
A MatchError is raised when a destructuring assignment statement fails, and thus MatchError is provided as a built-in for catching those errors. MatchError objects support two attributes, pattern, which is a string describing the failed pattern, and value, which is the object that failed to match that pattern.

:mrgreen:

Octave – istruzioni IV – 44

iron

Da qui oggi sono qui.

L’istruzione unwind_protect
Octave supports a limited form of exception handling modeled after the unwind-protect form of Lisp.
The general form of an unwind_protect block looks like this:

unwind_protect
  body
unwind_protect_cleanup
  cleanup
end_unwind_protect

where body and cleanup are both optional and may contain any Octave expressions or commands. The statements in cleanup are guaranteed to be executed regardless of how control exits body.

This is useful to protect temporary changes to global variables from possible errors. For example, the following code will always restore the original value of the global variable frobnosticate even if an error occurs in the first part of the unwind_protect block.

save_frobnosticate = frobnosticate;
unwind_protect
  frobnosticate = true;
  ...
unwind_protect_cleanup
  frobnosticate = save_frobnosticate;
end_unwind_protect

Without unwind_protect, the value of frobnosticate would not be restored if an error occurs while evaluating the first part of the unwind_protect block because evaluation would stop at the point of the error and the statement to restore the value would not be executed.

In addition to unwind_protect, Octave supports another form of exception handling, the try block.

No, niente esempi (ho googlato ma zilch); costruirne uno richiede tempo (che manca), forse aggiornerò😦
Intanto passo qui.

L’istruzione try
The original form of a try block looks like this:

try
  body
catch
  cleanup
end_try_catch

where body and cleanup are both optional and may contain any Octave expressions or commands. The statements in cleanup are only executed if an error occurs in body.

No warnings or error messages are printed while body is executing. If an error does occur during the execution of body, cleanup can use the functions lasterr or lasterror to access the text of the message that would have been printed, as well as its identifier. The alternative form,

try
  body
catch err
  cleanup
end_try_catch

will automatically store the output of lasterror in the structure err. See Errors and Warnings, for more information about the lasterr and lasterror functions.

Anche qui –sigh– niente esempio😦

Continuazione su più linee
In the Octave language, most statements end with a newline character and you must tell Octave to ignore the newline character in order to continue a statement from one line to the next. Lines that end with the characters ... are joined with the following line before they are divided into tokens by Octave’s parser. For example, the lines form a single statement.

o258

Any text between the continuation marker and the newline character is ignored. For example, the statement is equivalent to the one shown above.

o259

Uh! ‘na cosa: “comment two” manca del # richiesto ma funziona lo stesso, verifico:

o260

OK!, tutto il testo dopo ... viene ignorato. Da non approfittarne, nèh!😉

Inside double-quoted string constants, the character \ has to be used as continuation marker. The \ must appear at the end of the line just before the newline character:

o261

Input that occurs inside parentheses can be continued to the next line without having to use a continuation marker. For example, it is possible to write statements like

if (fine_dining_destination == on_a_boat
    || fine_dining_destination == on_a_train)
  seuss (i, will, not, eat, them, sam, i, am, i,
         will, not, eat, green, eggs, and, ham);
endif

without having to add to the clutter with continuation markers.

:mrgreen:

cit. & loll – 6

Basta ferie si torna al lavoro serio & (a volte) anche un tantino lolloso😀

muraro

We had already obtained the archive of NSA cyber weapons released earlier today and will release our own pristine copy in due course
::: wikileaks

When mathematicians provide source code for their algorithms
::: randal_olson

parecchie sorprese😀 & c’è chi considera le lingue; io sono andato in ordine cronologico contando solo i più importanti. Uh! non vince Java😳
::: hashtag

Companies: “Programmers love open-plan offices
::: Xof

Ho trovato qualcosa di più inutile del bagnino alle Olimpiadi
::: andreacolangelo

CorcFemWAAAHCMv.jpg:large

Everything should be as complex as possible, and then twice as complex again
::: drewm

On trying PowerShell
::: bridgetkromhout

Automation solves all problems
::: sunil_abraham

Best quote
::: Ken’s

Functional programmer: (noun)
::: jamesiry

fifa

Esiste un numero per donare soldi alla ricerca contro Windows 8?
::: lucaferrari15

Muthafuckin’ this!
::: peterseibel

Imagine there’s no crashes
::: johnregehr

how I got better at debugging
::: b0rk

move

Proofs
::: xkcd

20% of Scientific Papers On Genes Contain Conversion Errors Caused By Excel, Says Report
::: Slashdot

About 1,000 instructions is a reasonable upper limit for the complexity of problems now envisioned
::: CompSciFact

The most common programming language
::: georgeb3dr

shady-d.gif

Octave – istruzioni III – 43

Hellzapoppin'

Oggi copio qui continuando da qui.

L’istruzione for
The for statement makes it more convenient to count iterations of a loop. The general form of the for statement looks like this:

for var = expression
  body
endfor

where body stands for any statement or list of statements, expression is any valid expression, and var may take several forms. Usually it is a simple variable name or an indexed variable. If the value of expression is a structure, var may also be a vector with two elements.
The assignment expression in the for statement works a bit differently than Octave’s normal assignment statement. Instead of assigning the complete result of the expression, it assigns each column of the expression to var in turn. If expression is a range, a row vector, or a scalar, the value of var will be a scalar each time the loop body is executed. If var is a column vector or a matrix, var will be a column vector each time the loop body is executed.
The following example shows another way to create a vector containing the first ten elements of the Fibonacci sequence, this time using the for statement:

o250

This code works by first evaluating the expression 3:10, to produce a range of values from 3 to 10 inclusive. Then the variable i is assigned the first element of the range and the body of the loop is executed once. When the end of the loop body is reached, the next value in the range is assigned to the variable i, and the loop body is executed again. This process continues until there are no more elements to assign.

Within Octave is it also possible to iterate over matrices or cell arrays using the for statement. For example consider

o251

In this case the variable i takes on the value of the columns of the matrix or cell matrix. So the first loop iterates twice, producing two column vectors [1;2], followed by [3;4], and likewise for the loop over the cell array. This can be extended to loops over multi-dimensional arrays. For example:

o252

In the above case, the multi-dimensional matrix c is reshaped to a two-dimensional matrix as reshape (c, rows (c), prod (size (c)(2:end))) and then the same behavior as a loop over a two dimensional matrix is produced.

Although it is possible to rewrite all for loops as while loops, the Octave language has both statements because often a for loop is both less work to type and more natural to think of. Counting the number of iterations is very common in loops and it can be easier to think of this counting as part of looping rather than as something to do inside the loop.

Passo qui.

Ciclare sugli elementi di una struttura
A special form of the for statement allows you to loop over all the elements of a structure:

for [ val, key ] = expression
  body
endfor

In this form of the for statement, the value of expression must be a structure. If it is, key and val are set to the name of the element and the corresponding value in turn, until there are no more elements. For example:

o253

The elements are not accessed in any particular order. If you need to cycle through the list in a particular way, you will have to use the function fieldnames and sort the list yourself.

Avanti, sono qui.

L’istruzione break
The break statement jumps out of the innermost while, do-until, or for loop that encloses it. The break statement may only be used within the body of a loop. The following example finds the smallest divisor of a given integer, and also identifies prime numbers:

o254

When the remainder is zero in the first while statement, Octave immediately breaks out of the loop. This means that Octave proceeds immediately to the statement following the loop and continues processing. (This is very different from the exit statement which stops the entire Octave program.)

Here is another program equivalent to the previous one. It illustrates how the condition of a while statement could just as well be replaced with a break inside an if:

o255

Ancora una cosa, qui.

L’istruzione continue
The continue statement, like break, is used only inside while, do-until, or for loops. It skips over the rest of the loop body, causing the next cycle around the loop to begin immediately. Contrast this with break, which jumps out of the loop altogether. Here is an example:

o257

If one of the elements of vec is an odd number, this example skips the print statement for that element, and continues back to the first statement in the loop.

This is not a practical example of the continue statement, but it should give you a clear understanding of how it works. Normally, one would probably write the loop like this:

o257

break e continue, imho, devono essere utlizzati con parsimonia, sono parenti di go to👿

:mrgreen:

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:

Iscriviti

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

Segui assieme ad altri 95 follower