Coconut – utilities e considerazioni conclusive – 13

super-metal

Proseguendo da qui oggi copio qui, dove si parla di utilities. E poi concludo (per adesso).

Syntax Highlighting
Si può fare con Sublime Text, Pygments o altri metodi ancora.
Interessa? Pygments mi sembra sexy; non fosse che sono vecchio e per via di quello che adesso racconto.

Si può usare Coconut?
Secondo me sì ma ci sono alcune issues da addressare questioni da affrontare:

  • Coconut è nuovo e (per quel che ne so) personale, sviluppato dal solo Evan Hubinger, rockz😀
  • sarebbe un altro linguaggio da imparare, sono già troppi;
  • per ragioni misteriose i linguaggi funzionali sono visti con diffidenza.

Illustro con un paio di esempi, spero indicativi.

c59

Quale delle due scritture è più naturale? Forse solo questione di abitudini ma…

Inoltre supponiamo che il codice Coconut sia contenuto nel file e.coco:

from math import exp
1 |> exp |> print

che compilo

c60

Il file risultante e.py è OK, nel senso che può essere eseguito

c61

ma è disastrosamente lungo e casinato

c62

Aprendolo e copiando le ultime due righe dentro Python (cosa che potrebbe capitare in caso di manutenzione, se si evita il file Coconut) si ottiene un codice eseguibile:

c63

quasi. Un caso più realistico (anche se sempre finto) è quello in cui il file .coco sia un modulo, come nel caso minimo val_const.coco:

from math import exp

def val_e():
    match t = 1 |> exp
    return t

che posso compilare e usare con Python:

c64

OK. Però, al solito il codice .py prodotto è lungo

c65

e –soprattutto– immodificabile all’interno di Python, per la manutenzione serve Coconut.

Quindi, in conclusione: Coconut mi piace, da monitorare, vedere se cresce. Per l’uso è da valutare all’interno del proprio ecosistema (cit.), è un altro linguaggio il cui apprendimento richiede risorse.
Mi è inoltre stato fatto notare che esistono progetti simili, chissà l’evoluzione… (visto che non cito Niels Bohr?)😀

:mrgreen:

Octave – funzioni e scripts III – 47

Schedel

Continuo, oggi qui.

Lista degli argomenti di lunghezza variabile
Sometimes the number of input arguments is not known when the function is defined. As an example think of a function that returns the smallest of all its input arguments. For example:

a = smallest (1, 2, 3);
b = smallest (1, 2, 3, 4);

In this example both a and b would be 1. One way to write the smallest function is

function val = smallest (arg1, arg2, arg3, arg4, arg5)
  body
endfunction

and then use the value of nargin to determine which of the input arguments should be considered. The problem with this approach is that it can only handle a limited number of input arguments.

If the special parameter name varargin appears at the end of a function parameter list it indicates that the function takes a variable number of input arguments. Using varargin the function looks like this

function val = smallest (varargin)
  body
endfunction

In the function body the input arguments can be accessed through the variable varargin. This variable is a cell array containing all the input arguments. See Cell Arrays, for details on working with cell arrays. The smallest function can now be defined like this

o282

This implementation handles any number of input arguments, but it’s also a very simple solution to the problem.

A slightly more complex example of varargin is a function print_arguments that prints all input arguments. Such a function can be defined like this

o283

Function File: [reg, prop] = parseparams (params)
Function File: [reg, var1, ...] = parseparams (params, name1, default1, ...)

Return in reg the cell elements of param up to the first string element and in prop all remaining elements beginning with the first string element.

o284

The parseparams function may be used to separate regular numeric arguments from additional arguments given as property/value pairs of the varargin cell array.
In the second form of the call, available options are specified directly with their default values given as name-value pairs. If params do not form name-value pairs, or if an option occurs that does not match any of the available options, an error occurs.
When called from an m-file function, the error is prefixed with the name of the caller function.
The matching of options is case-insensitive.

Avanti, sono qui.

Ignorare argomenti
In the formal argument list, it is possible to use the dummy placeholder ~ instead of a name. This indicates that the corresponding argument value should be ignored and not stored to any variable.

function val = pick2nd (~, arg2)
  val = arg2;
endfunction

The value of nargin is not affected by using this declaration.
Return arguments can also be ignored using the same syntax. Functions may take advantage of ignored outputs to reduce the number of calculations performed. To do so, use the isargout function to query whether the output argument is wanted. For example:

function [out1, out2] = long_function (x, y, z)
  if (isargout (1))
    ## Long calculation
    ...
    out1 = result;
  endif
  ...
endfunction

mahhh…😳

Built-in Function: isargout (k)
Within a function, return a logical value indicating whether the argument k will be assigned to a variable on output.
If the result is false, the argument has been ignored during the function call through the use of the tilde (~) special output argument. Functions can use isargout to avoid performing unnecessary calculations for outputs which are unwanted.
If k is outside the range 1:max (nargout), the function returns false. k can also be an array, in which case the function works element-by-element and a logical array is returned. At the top level, isargout returns an error.

Passo avanti, qui.

Ritornare una lista di lunghezza variabile
It is possible to return a variable number of output arguments from a function using a syntax that’s similar to the one used with the special varargin parameter name. To let a function return a variable number of output arguments the special output parameter name varargout is used. As with varargin, varargout is a cell array that will contain the requested output arguments.
As an example the following function sets the first output argument to 1, the second to 2, and so on.

o285

If varargin (varargout) does not appear as the last element of the input (output) parameter list, then it is not special, and is handled the same as any other parameter name.

Function File: [r1, r2, ..., rn] = deal (a)
Function File: [r1, r2, ..., rn] = deal (a1, a2, ..., an)

Copy the input parameters into the corresponding output parameters.
If only a single input parameter is supplied, its value is copied to each of the outputs.

o286

Nota: volendo (ma probabilmente non volete, vero?) si può scrivere anche così:

o287

Programming Note: deal is often used with comma separated lists derived from cell arrays or structures. This is unnecessary as the interpreter can perform the same action without the overhead of a function call. For example:

o288

:mrgreen:

Octave – funzioni e scripts II – 46

pleiades

Continuo da qui, copio qui.

Ritornare più valori
Unlike many other computer languages, Octave allows you to define functions that return more than one value. The syntax for defining functions that return multiple values is

function [ret-list] = name (arg-list)
  body
endfunction

where name, arg-list, and body have the same meaning as before, and ret-list is a comma-separated list of variable names that will hold the values returned from the function. The list of return values must have at least one element. If ret-list has only one element, this form of the function statement is equivalent to the form described in the previous section.

Here is an example of a function that returns two values, the maximum element of a vector and the index of its first occurrence in the vector.

o269

In this particular case, the two values could have been returned as elements of a single array, but that is not always possible or convenient. The values to be returned may not have compatible dimensions, and it is often desirable to give the individual return values distinct names.

Nota (dal post precedente): si ovvio che si può scrivere:

o270

It is possible to use the nthargout function to obtain only some of the return values or several at once in a cell array. See Cell Array Objects.

Function File: nthargout (n, func, ...)
Function File: nthargout (n, ntot, func, ...)

Return the nth output argument of the function specified by the function handle or string func.
Any additional arguments are passed directly to func. The total number of arguments to call func with can be passed in ntot; by default ntot is n. The input n can also be a vector of indices of the output, in which case the output will be a cell array of the requested output arguments.
The intended use nthargout is to avoid intermediate variables. For example, when finding the indices of the maximum entry of a matrix, the following two compositions of nthargout

o271

are completely equivalent to the following lines:

o272

It can also be helpful to have all output arguments in a single cell in the following manner: USV = nthargout ([1:3], @svd, hilb (5));

Uhmmm… chissà se si dovrà usare tutta questa roba👿 Vero che certe funzioni sono specialistiche (troppo, spero)😳

In addition to setting nargin each time a function is called, Octave also automatically initializes nargout to the number of values that are expected to be returned. This allows you to write functions that behave differently depending on the number of values that the user of the function has requested. The implicit assignment to the built-in variable ans does not figure in the count of output arguments, so the value of nargout may be zero.

The svd and lu functions are examples of built-in functions that behave differently depending on the value of nargout.
Ah, ecco😀

It is possible to write functions that only set some return values. For example, calling the function

o273

as

o274

yesss, with a warning😀

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

Report the number of output arguments from a function.
Called from within a function, return the number of values the caller expects to receive. At the top level, nargout with no argument is undefined and will produce an error.
If called with the optional argument fcn —a function name or handle— return the number of declared output values that the function can produce.
If the final output argument is varargout the returned value is negative.
For example, f () will cause nargout to return 0 inside the function f and [s, t] = f () will cause nargout to return 2 inside the function f.

Non sono riuscito a riprodurre tutto, solo questo

o275

In the second usage,

o276

will return 2, because histc has two outputs, whereas

o277

will return -2, because imread has two outputs and the second is varargout.

Programming Note. nargout does not work for built-in functions and returns -1 for all anonymous functions.

It is good practice at the head of a function to verify that it has been called correctly. In Octave the following idiom is seen frequently

if (nargin < min_#_inputs || nargin > max_#_inputs)
  print_usage ();
endif

which stops the function execution and prints a message about the correct way to call the function whenever the number of inputs is wrong.

For compatibility with MATLAB, narginchk and nargoutchk are available which provide similar error checking.

Function File: narginchk (minargs, maxargs)
Check for correct number of input arguments.
Generate an error message if the number of arguments in the calling function is outside the range minargs and maxargs. Otherwise, do nothing.
Both minargs and maxargs must be scalar numeric values. Zero, Inf, and negative values are all allowed, and minargs and maxargs may be equal.
Note that this function evaluates nargin on the caller.

Function File: nargoutchk (minargs, maxargs)
Function File: msgstr = nargoutchk (minargs, maxargs, nargs)
Function File: msgstr = nargoutchk (minargs, maxargs, nargs, "string")
Function File: msgstruct = nargoutchk (minargs, maxargs, nargs, "struct")

Check for correct number of output arguments.
In the first form, return an error if the number of arguments is not between minargs and maxargs. Otherwise, do nothing. Note that this function evaluates the value of nargout on the caller so its value must have not been tampered with.
Both minargs and maxargs must be numeric scalars. Zero, Inf, and negative are all valid, and they can have the same value.
For backwards compatibility, the other forms return an appropriate error message string (or structure) if the number of outputs requested is invalid.
This is useful for checking to that the number of output arguments supplied to a function is within an acceptable range.

Besides the number of arguments, inputs can be checked for various properties. validatestring is used for string arguments and validateattributes for numeric arguments.

Function File: validstr = validatestring (str, strarray)
Function File: validstr = validatestring (str, strarray, funcname)
Function File: validstr = validatestring (str, strarray, funcname, varname)
Function File: validstr = validatestring (..., position)

Verify that str is an element, or substring of an element, in strarray.
When str is a character string to be tested, and strarray is a cellstr of valid values, then validstr will be the validated form of str where validation is defined as str being a member or substring of validstr. This is useful for both verifying and expanding short options, such as "r", to their longer forms, such as "red". If str is a substring of validstr, and there are multiple matches, the shortest match will be returned if all matches are substrings of each other. Otherwise, an error will be raised because the expansion of str is ambiguous. All comparisons are case insensitive.
The additional inputs funcname, varname, and position are optional and will make any generated validation error message more specific.

o278

Function File: validateattributes (A, classes, attributes)
Function File: validateattributes (A, classes, attributes, arg_idx)
Function File: validateattributes (A, classes, attributes, func_name)
Function File: validateattributes (A, classes, attributes, func_name, arg_name)
Function File: validateattributes (A, classes, attributes, func_name, arg_name, arg_idx)

Check validity of input argument.
Confirms that the argument A is valid by belonging to one of classes, and holding all of the attributes. If it does not, an error is thrown, with a message formatted accordingly. The error message can be made further complete by the function name fun_name, the argument name arg_name, and its position in the input arg_idx.
classes must be a cell array of strings (an empty cell array is allowed) with the name of classes (remember that a class name is case sensitive). In addition to the class name, the following categories names are also valid:

  • "float" Floating point value comprising classes "double" and "single".
  • "integer" Integer value comprising classes (u)int8, (u)int16, (u)int32, (u)int64.
  • "numeric" Numeric value comprising either a floating point or integer value.

attributes must be a cell array with names of checks for A. Some of them require an additional value to be supplied right after the name (see details for each below).

  • "<=" All values are less than or equal to the following value in attributes.
  • "<" All values are less than the following value in attributes.
  • ">=" All values are greater than or equal to the following value in attributes.
  • ">" All values are greater than the following value in attributes.
  • "2d" A 2-dimensional matrix. Note that vectors and empty matrices have 2 dimensions, one of them being of length 1, or both length 0.
  • "3d" Has no more than 3 dimensions. A 2-dimensional matrix is a 3-D matrix whose 3rd dimension is of length 1.
  • "binary" All values are either 1 or 0.
  • "column" Values are arranged in a single column.
  • "decreasing" No value is NaN, and each is less than the preceding one.
  • "even" All values are even numbers.
  • "finite" All values are finite.
  • "increasing" No value is NaN, and each is greater than the preceding one.
  • "integer" All values are integer. This is different than using isinteger which only checks its an integer type. This checks that each value in A is an integer value, i.e., it has no decimal part.
  • "ncols" Has exactly as many columns as the next value in attributes.
  • "ndims" Has exactly as many dimensions as the next value in attributes.
  • "nondecreasing" No value is NaN, and each is greater than or equal to the preceding one.
  • "nonempty" It is not empty.
  • "nonincreasing" No value is NaN, and each is less than or equal to the preceding one.
  • "nonnan" No value is a NaN.
  • "nonnegative" All values are non negative.
  • "nonsparse" It is not a sparse matrix.
  • "nonzero" No value is zero.
  • "nrows" Has exactly as many rows as the next value in attributes.
  • "numel" Has exactly as many elements as the next value in attributes.
  • "odd" All values are odd numbers.
  • "positive" All values are positive.
  • "real" It is a non-complex matrix.
  • "row" Values are arranged in a single row.
  • "scalar" It is a scalar.
  • "size" Its size has length equal to the values of the next in attributes. The next value must is an array with the length for each dimension. To ignore the check for a certain dimension, the value of NaN can be used.
  • "square" Is a square matrix.
  • "vector" Values are arranged in a single vector (column or vector).

If none of the preceding functions is sufficient there is also the class inputParser which can perform extremely complex input checking for functions.

Function File: p = inputParser ()
Create object p of the inputParser class.

This class is designed to allow easy parsing of function arguments. The class supports four types of arguments:

  • mandatory (see addRequired);
  • optional (see addOptional);
  • named (see addParamValue);
  • switch (see addSwitch).

After defining the function API with these methods, the supplied arguments can be parsed with the parse method and the parsing results accessed with the Results accessor.

Accessor method: inputParser.Parameters
Return list of parameter names already defined.

Accessor method: inputParser.Results
Return structure with argument names as fieldnames and corresponding values.

Accessor method: inputParser.Unmatched
Return structure similar to Results, but for unmatched parameters. See the KeepUnmatched property.

Accessor method: inputParser.UsingDefaults
Return cell array with the names of arguments that are using default values.

Class property: inputParser.CaseSensitive = boolean
Set whether matching of argument names should be case sensitive. Defaults to false.

Class property: inputParser.FunctionName = name
Set function name to be used in error messages; Defaults to empty string.

Class property: inputParser.KeepUnmatched = boolean
Set whether an error should be given for non-defined arguments. Defaults to false. If set to true, the extra arguments can be accessed through Unmatched after the parse method. Note that since Switch and ParamValue arguments can be mixed, it is not possible to know the unmatched type. If argument is found unmatched it is assumed to be of the ParamValue type and it is expected to be followed by a value.

Class property: inputParser.StructExpand = boolean
Set whether a structure can be passed to the function instead of parameter/value pairs. Defaults to true. Not implemented yet.

The following example shows how to use this class:

o279

allora…

  • check ("mech");           # valid, use defaults for other arguments
  • check ();                 # error, one argument is mandatory
  • check (1);                # error, since ! ischar
  • check ("mech", "~/dev");  # valid, use defaults for other arguments
  • check ("mech", "~/dev", [0 1 0 0], "type", "linear");  # valid

o280

e ancora…

o281

Uhmmmm… niente errore per l’ultima chiamata😳

Note 1: A function can have any mixture of the four API types but they must appear in a specific order. Required arguments must be first and can be followed by any Optional arguments. Only the ParamValue and Switch arguments may be mixed together and they must appear at the end.
Note 2: If both Optional and ParamValue arguments are mixed in a function API then once a string Optional argument fails to validate it will be considered the end of the Optional arguments. The remaining arguments will be compared against any ParamValue or Switch arguments.

:mrgreen:

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:

Iscriviti

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

Segui assieme ad altri 93 follower