Coconut – keywords I

proxy

Continuo con le keywords, da qui, copiando qui.

match

Coconut provides fully-featured, functional pattern-matching through its match statements.

Overview
match statements follow the basic syntax match <pattern> in <value>. The match statement will attempt to match the value against the pattern, and if successful, bind any variables in the pattern to whatever is in the same position in the value, and execute the code below the match statement. match statements also support, in their basic syntax, an if <cond> that will check the condition after executing the match before executing the code below, and an else statement afterwards that will only be executed if the match statement is not. What is allowed in the match statement’s pattern has no equivalent in Python, and thus the specifications below are provided to explain it.

Syntax Specification
Coconut match statement syntax is

match <pattern> in <value> [if <cond>]:
    <body>
[else:
    <body>]

where <value> is the item to match against, <cond> is an optional additional check, and <body> is simply code that is executed if the header above it succeeds. <pattern> follows its own, special syntax, defined roughly like so:

pattern ::= (
    "(" pattern ")"                 # parentheses
    | "None" | "True" | "False"     # constants
    | "=" NAME                      # check
    | NUMBER                        # numbers
    | STRING                        # strings
    | [pattern "as"] NAME           # capture
    | NAME "(" patterns ")"         # data types
    | "(" patterns ")"              # sequences can be in tuple form
    | "[" patterns "]"              #  or in list form
    | "(|" patterns "|)"            # lazy lists
    | "{" pattern_pairs "}"         # dictionaries
    | ["s"] "{" pattern_consts "}"  # sets
    | (                             # head-tail splits
        "(" patterns ")"
        | "[" patterns "]"
      ) "+" pattern
    | pattern "+" (                 # init-last splits
        "(" patterns ")"
        | "[" patterns "]"
      )
    | (                             # head-last splits
        "(" patterns ")"
        | "[" patterns "]"
      ) "+" pattern "+" (
        "(" patterns ")"            # this match must be the same
        | "[" patterns "]"          #  construct as the first match
      )
    | (                             # iterator splits
        "(" patterns ")"
        | "[" patterns "]"
        | "(|" patterns "|)"        # lazy lists
      ) "::" pattern
    | pattern "is" exprs            # type-checking
    | pattern "and" pattern         # match all
    | pattern "or" pattern          # match any
    )

😳 panico?

Semantic Specification
match statements will take their pattern and attempt to “match” against it, performing the checks and deconstructions on the arguments as specified by the pattern. The different constructs that can be specified in a pattern, and their function, are:

  • Constants, Numbers, and Strings: will only match to the same constant, number, or string in the same position in the arguments.
  • Variables: will match to anything, and will be bound to whatever they match to, with some exceptions:
    • If the same variable is used multiple times, a check will be performed that each use match to the same value.
    • If the variable name _ is used, nothing will be bound and everything will always match to it.
  • Explicit Bindings (<pattern> as <var>): will bind <var> to <pattern>.
  • Checks (=<var>): will check that whatever is in that position is equal to the previously defined variable <var>.
  • Type Checks (<var> is <types>): will check that whatever is in that position is of type(s) <types> before binding the <var>.
  • Data Types (<name>(<args>)): will check that whatever is in that position is of data type <name> and will match the attributes to <args>.
  • Lists ([<patterns>]), Tuples ((<patterns>)), or lazy lists ((|<patterns>|)): will only match a sequence (collections.abc.Sequence) of the same length, and will check the contents against <patterns>.
  • Dicts ({<pairs>}): will only match a mapping (collections.abc.Mapping) of the same length, and will check the contents against <pairs>.
  • Sets ({<constants>}): will only match a set (collections.abc.Set) of the same length and contents.
  • Head-Tail Splits (<list/tuple> + <var>): will match the beginning of the sequence against the <list/tuple>, then bind the rest to <var>, and make it the type of the construct used.
  • Init-Last Splits (<var> + <list/tuple>): exactly the same as head-tail splits, but on the end instead of the beginning of the sequence.
  • Head-Last Splits (<list/tuple> + <var> + <list/tuple>): the combination of a head-tail and an init-last split.
  • Iterator Splits (<list/tuple/lazy list> :: <var>, or <lazy list>): will match the beginning of an iterable (collections.abc.Iterable) against the <list/tuple/lazy list>, then bind the rest to <var> or check that the iterable is done.

When checking whether or not an object can be matched against in a particular fashion, Coconut makes use of Python’s abstract base classes. Therefore, to enable proper matching for a custom object, register it with the proper abstract base classes.

Examples:

c31

Showcases else statements, which work much like else statements in Python: the code under an else statement is only executed if the corresponding match fails.

c32

Showcases matching to data types. Values defined by the user with the data statement can be matched against and their contents accessed by specifically referencing arguments to the data type’s constructor.

c33

Showcases how the combination of data types and match statements can be used to powerful effect to replicate the usage of algebraic data types in other functional programming languages.

c34

Showcases head-tail splitting, one of the most common uses of pattern-matching, where a + <var> (or :: <var> for any iterable) at the end of a list or tuple literal can be used to match the rest of the sequence.
E naturalmente il gioco può continuare (l’idea della pipe, Douglas McIlroy et al. (tanti al. anche prima) è fantastica):

c35

With Pythoncan’t be done without a long series of checks for each match statement. See the compiled code for the Python syntax.
Un’osservazione non so quanto valida: il codice prodotto dalla compilazione di Coconut è sempree molto poco leggibile, OK se è finale, altrimenti richiede pazienza, assay😉

:mrgreen:

SICP – cap. 1 – Esempio: test di primalità – esercizi – 34

1326

Continuo da qui a copiare qui.

Exercise 1.28 One variant of the Fermat test that cannot be fooled is called the Miller-Rabin test (Miller 1976; Rabin 1980). This starts from an alternate form of Fermat’s Little Theorem, which states that if n is a prime number and a is any positive integer less than n, then a raised to the (n - 1)st power is congruent to 1 modulo n. To test the primality of a number n by the Miller-Rabin test, we pick a random number a<n and raise a to the (n - 1)st power modulo n using the expmod procedure. However, whenever we perform the squaring step in expmod, we check to see if we have discovered a “nontrivial square root of 1 modulo n,” that is, a number not equal to 1 or n - 1 whose square is equal to 1 modulo n. It is possible to prove that if such a nontrivial square root of 1 exists, then n is not prime. It is also possible to prove that if n is an odd number that is not prime, then, for at least half the numbers a<n, computing an-1 in this way will reveal a nontrivial square root of 1 modulo n. (This is why the Miller-Rabin test cannot be fooled.) Modify the expmod procedure to signal if it discovers a nontrivial square root of 1, and use this to implement the Miller-Rabin test with a procedure analogous to fermat-test. Check your procedure by testing various known primes and non-primes. Hint: One convenient way to make expmod signal is to have it return 0.

Panico. Davvero. No, dai basta procedere passo-passo e si può fare (btl.rkt):

(require (lib "27.ss" "srfi"))

(define (square-check x m)
  (if (and (not (or (= x 1) (= x (- m 1))))
           (= (remainder (* x x) m) 1))
      0
      (remainder (* x x) m)))

(define (even? n)
  (= (remainder n 2) 0))

(define (expmod base exp m)
  (cond ((= exp 0) 1)
        ((even? exp)
          (square-check (expmod base (/ exp 2) m) m))
        (else
          (remainder (* base (expmod base (- exp 1) m))
                     m))))

(define (miller-rabin-test n)
  (define (try-it a)
     (= (expmod a (- n 1) n) 1))
  (try-it (+ 2 (random-integer (- n 2)))))

s62

ho copiato Bill the Lizard😀

Altrettanto bella la versione di Ken Dick (kd.rkt):

#lang racket

(define (square x)
  (* x x))

(define (expmod-with-trivial-sqrt-check base exp m)
  (cond ((= exp 0) 1)
        ((even? exp)
         (let* ((intermediate
                 (expmod-with-trivial-sqrt-check base (/ exp 2) m))
                (squared-mod (remainder (square intermediate) m)))
           (if (and (not
                     (or (= intermediate 1) (= intermediate (- m 1))))
                    (= squared-mod 1))
               0
               squared-mod)))
        (else
         (remainder
          (* base (expmod-with-trivial-sqrt-check base (- exp 1) m))
          m))))

(define (miller-rabin-test n)
  (define (try-it a )
    (= (expmod-with-trivial-sqrt-check a (- n 1) n) 1))
  (try-it (+ 1 (random (- n 1)))))

Non metto lo screenshot perché identico al precedente.

Su s-sol due soluzioni, con considerazioni interessanti (per esempio sul let che SICP finora non ha introdotto).

SICP richiederebbe più tempo, lo so😳
:mrgreen:

Octave – data containers – manipolare structures – 28

proxy2

Sempre strutture, da qui, copiando qui.

Manipolare structures
Functions that can manipulate the fields of a structure.

Built-in Function: numfields (s)
Return the number of fields of the structure s.

o166

Function File: names = fieldnames (struct)
Function File: names = fieldnames (obj)
Function File: names = fieldnames (javaobj)
Function File: names = fieldnames ("jclassname")

Return a cell array of strings with the names of the fields in the specified input.
When the input is a structure struct, the names are the elements of the structure.
When the input is an Octave object obj, the names are the public properties of the object.
When the input is a Java object javaobj or Java classname jclassname the name are the public data elements of the object or class.

o167

Built-in Function: isfield (x, "name")
Built-in Function: isfield (x, name)

Return true if the x is a structure and it includes an element named name.
If name is a cell array of strings then a logical array of equal dimension is returned.

o168

Function File: sout = setfield (s, field, val)
Function File: sout = setfield (s, sidx1, field1, fidx1, sidx2, field2, fidx2, ..., val)

Return a copy of the structure s with the field member field set to the value val.

o169

This is equivalent to s.("foo bar") = 42.
Note that ordinary structure syntax s.foo bar = 42 cannot be used here, as the field name is not a valid Octave identifier because of the space character. Using arbitrary strings for field names is incompatible with MATLAB, and this usage will emit a warning if the warning ID Octave:language-extension is enabled. See
XREFwarning_ids.

With the second calling form, set a field of a structure array. The input sidx selects an element of the structure array, field specifies the field name of the selected element, and fidx selects which element of the field (in the case of an array or cell array). The sidx, field, and fidx inputs can be repeated to address nested structure array elements. The structure array index and field element index must be cell arrays while the field name must be a string.

o170

The example begins with an ordinary scalar structure to which a nested scalar structure is added. In all cases, if the structure index sidx is not specified it defaults to 1 (scalar structure). Thus, the example above could be written more concisely as setfield (s, "foo", "bar", 54).

Finally, an example with nested structure arrays:

o171

Here sa is a structure array whose field at elements 1 and 2 is in turn another structure array whose third element is a simple scalar structure. The terminal scalar structure has a field which contains a matrix value.

Cioè, vediamo se ho capito:

o172

OK!, pastissun😳

Note that the same result as in the above example could be achieved by:

o173

Function File: val = getfield (s, field)
Function File: val = getfield (s, sidx1, field1, fidx1, ...)

Get the value of the field named field from a structure or nested structure s.
If s is a structure array then sidx selects an element of the structure array, field specifies the field name of the selected element, and fidx selects which element of the field (in the case of an array or cell array). See setfield for a more complete description of the syntax.

o174

Built-in Function: sout = rmfield (s, "f")
Built-in Function: sout = rmfield (s, f)

Return a copy of the structure (array) s with the field f removed.
If f is a cell array of strings or a character array, remove each of the named fields.

o175

Function File: sout = orderfields (s1)
Function File: sout = orderfields (s1, s2)
Function File: sout = orderfields (s1, {cellstr})
Function File: sout = orderfields (s1, p)
Function File: [sout, p] = orderfields (...)

Return a copy of s1 with fields arranged alphabetically, or as specified by the second input.
Given one input struct s1, arrange field names alphabetically.
If a second struct argument is given, arrange field names in s1 as they appear in s2. The second argument may also specify the order in a cell array of strings cellstr. The second argument may also be a permutation vector.
The optional second output argument p is the permutation vector which converts the original name order to the new name order.

o175

o176

o177

o178

Function File: substruct (type, subs, ...)
Create a subscript structure for use with subsref or subsasgn.

o179

:mrgreen:

CS timeline

shopt

Una segnalazione, forse incompleta o forse non ancora completa che –colpa mia– avevo messo in un memo poi dimenticato. Ma ritrovato cercando altro (che sono sicuro c’è ma non riesco a trovare).
Uno dei miei interessi è l’aspetto storico dell’informatica, non solo nelle sue ultime manifestazioni. Anzi non ho nemmeno più il telefono: non sono mobile😳

Il prof Scott Aaronson compila l’elenco dei fatti fondamentali riguardanti la Computer Science. Per adesso ho questi due link:

Poi attraverso i commenti è possibile –non devo certo ricordare queste cose, vero? Enjoy😀

Il blog di Scott (bello il nome anche se richiede una googlata) purtroppo non lo seguo come meriterebbe ma spero di riuscire a intercettare eventuali sviluppi (m’interessano) e aggiornare questo post.

cit. & LOLL – 2

Fa caldo —forse l’ho già detto— ma ecco…

CoWWTt9W8AA6p-G

My new obsession: look at webpage sources for every site I visit, trying to guess the CMS they use
::: marcodelmastro

Ooooops! #PokemonGO
::: Lovelovingvio

Running your Perl or shell script for the first time
::: Google+

The Evolution of Language
::: Philip Wadler

I know I am not the only one. You think the same, don’t you?
::: itsfoss

Cn8NtcvW8AELqSN

In case you forgot one of the most important laws of the universe, there’s this
::: jessysaurusrex

Apparently everyone in my feed is watching something else
::: lizardbill

yeah… don’t worry about the robot apocalypse
::: internetofshit

Infinite recursion
::: ThePracticalDev

git merge
::: ThePracticalDev

I will build a great std::barrier to keep JavaScript programmers out
‘mericana ma lollosissimissima
::: isotrumpp

2fb44052-e4a6-40f5-b3bf-e751c2c1c2f6

Io così
::: ilpipotto

#ChuckNorris ha catturato tutti i 720 #Pokemon
::: Chucckk_Norris

The Problem with Programming
::: kOoLiNuS

After watching so many senior Democrats demonize encryption technology
::: csoghoian

Devhumor – humor for developers
appena coperto (& ‘niziato a copiare)
::: Devhumor

d8d96e190891f0dee3f70ae5e4c0e3a7

Octave – data containers – creare structures – 27

wizard-of-oz-6

Sempre sulle structures, proseguendo da qui copio qui.

Creare structures
Besides the index operator “.“, Octave can use dynamic naming “(var)” or the struct function to create structures. Dynamic naming uses the string value of a variable as the field name. For example:

o160

Dynamic indexing also allows you to use arbitrary strings, not merely valid Octave identifiers (note that this does not work on MATLAB):

o161

The warning id Octave:language-extension can be enabled to warn about this usage. See warning_ids.
Perso: mah… serve? o fa solo confusione?😦

More realistically, all of the functions that operate on strings can be used to build the correct field name before it is entered into the data structure.

o162

The third way to create structures is the struct command. struct takes pairs of arguments, where the first argument in the pair is the fieldname to include in the structure and the second is a scalar or cell array, representing the values to include in the structure or structure array. For example:

o163

Built-in Function: s = struct ()
Built-in Function: s = struct (field1, value1, field2, value2, ...)
Built-in Function: s = struct (obj)

Create a scalar or array structure and initialize its values.
The field1, field2, … variables are strings specifying the names of the fields and the value1, value2, … variables can be of any type.
If the values are cell arrays, create a structure array and initialize its values. The dimensions of each cell array of values must match. Singleton cells and non-cell values are repeated so that they fill the entire array. If the cells are empty, create an empty structure array with the specified field names.
If the argument is an object, return the underlying struct.

Observe that the syntax is optimized for struct arrays. Consider the following examples:

o164

he first case is an ordinary scalar struct—one field, one value. The second produces an empty struct array with one field and no values, since being passed an empty cell array of struct array values. When the value is a cell array containing a single entry, this becomes a scalar struct with that single entry as the value of the field. That single entry happens to be an empty cell array.
Finally, if the value is a non-scalar cell array, then struct produces a struct array.

The function isstruct can be used to test if an object is a structure or a structure array.

Built-in Function: isstruct (x)
Return true if x is a structure or a structure array.

o165

:mrgreen:

Octave – data containers – 26

1-ornlresearch

Sempre sulle structures, qui, proseguendo da qui.
Structure Arrays
A structure array is a particular instance of a structure, where each of the fields of the structure is represented by a cell array. Each of these cell arrays has the same dimensions. Conceptually, a structure array can also be seen as an array of structures with identical fields. An example of the creation of a structure array is

o152

which creates a 2-by-1 structure array with two fields. Another way to create a structure array is with the struct function (see Creating Structures). As previously, to print the value of the structure array, you can type its name:

o153

Individual elements of the structure array can be returned by indexing the variable like x(1), which returns a structure with two fields:

o154

Furthermore, the structure array can return a comma separated list of field values (see Comma Separated Lists), if indexed by one of its own field names. For example:

o155

Here is another example, using this comma separated list on the left-hand side of an assignment:

o156

Just as for numerical arrays, it is possible to use vectors as indices (see Index Expressions):

0157

The function size will return the size of the structure. For the example above

o158

Elements can be deleted from a structure array in a similar manner to a numerical array, by assigning the elements to an empty matrix. For example

o159

:mrgreen:

Octave – data containers – 25

MK2-1

Finite le stringhe, qui, oggi argomento nuovo, copio qui.

Data containers

Octave includes support for two different mechanisms to contain arbitrary data types in the same variable. Structures, which are C-like, and are indexed with named fields, and cell arrays, where each element of the array can have a different data type and or shape. Multiple input arguments and return values of functions are organized as another data container, the comma separated list.

OK, pronto per le structures, qui

Structures
Octave includes support for organizing data in structures. The current implementation uses an associative array with indices limited to strings, but the syntax is more like C-style structures.

Ahemmm… solo una lista di altre pagine, passo qui.

Here are some examples of using data structures in Octave.
Elements of structures can be of any value type. For example, the three expressions

o146

The ‘.’ character separates the structure name from the field name and indicates to Octave that this variable is a structure.

Note that Octave may print the elements in any order.

Structures may be copied just like any other variable:

o147

Since structures are themselves values, structure elements may reference other structures. The following statements change the value of the element b of the structure x to be a data structure containing the single element d, which has a value of 3.

o148

L’esempio proposto mi da errore, ho modificato il codice ottenendo infine il risultato voluto.

Note that when Octave prints the value of a structure that contains other structures, only a few levels are displayed. For example:

o149

This prevents long and confusing output from large deeply nested structures. The number of levels to print for nested structures may be set with the function struct_levels_to_print, and the function print_struct_array_contents may be used to enable printing of the contents of structure arrays.

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

Query or set the internal variable that specifies the number of structure levels to display.
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.

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

Query or set the internal variable that specifies whether to print struct array contents.
If true, values of struct array elements are printed. This variable does not affect scalar structures whose elements are always printed. In both cases, however, printing will be limited to the number of levels specified by struct_levels_to_print.
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.

Functions can return structures. For example, the following function separates the real and complex parts of a matrix and stores them in two elements of the same structure variable.

o150

When called with a complex-valued argument, f returns the data structure containing the real and imaginary parts of the original function argument.

o151

Function return lists can include structure elements, and they may be indexed like any other variable. For example: no mi da errore😦
Dovrebbe essere

[ x.u, x.s(2:3,2:3), x.v ] = svd ([1, 2; 3, 4]);
x
     ⇒ x =
        {
          u =

            -0.40455  -0.91451
            -0.91451   0.40455

          s =

             0.00000   0.00000   0.00000
             0.00000   5.46499   0.00000
             0.00000   0.00000   0.36597

          v =

            -0.57605   0.81742
            -0.81742  -0.57605

        }

It is also possible to cycle through all the elements of a structure in a loop, using a special form of the for statement (see Looping Over Structure Elements).

:mrgreen:

Visto nel Web – 245

Attività ridotta mia e ontehtoobz; cmq ecco cosa ho visto nel Web.

Cn7cihTWYAA5Hat

Inter-Procedural Optimization and Derefinement
#:linguaggi di programmazione
::: Playing With Pointers

Orc
is a novel language for distributed and concurrent programming
#:linguaggi di programmazione
::: Orc Language Project

“E’ iniziato il cambiamento.” Anche l’#Atac assume personale affetto da disturbo paranoide della personalità?
#:social media
::: _odisseus

Glumpy
Glumpy is a python library for scientific visualization that is both fast, scalable and beautiful.
#:programming, codice, snippet
::: Glumpy

Email o social media?
io sono per l’Email
#:Web, Internet
::: Sergio Gridelli

w10

Del malcostume di copiare gli articoli senza citare la fonte
#:Web, Internet
::: Dario Cavedon

Interviewing my mother, a mainframe COBOL programmer
divertentissimo😉
#:storia
::: Medium

A new atomic hard drive could store all of Earth’s books on a postage stamp
#:innovazioni, futuro
::: SAI

#digitalhumanities tutorials – definitely on my ‘to do’ list this summer
#:storia
::: Tor_Barker

WikiLeaks Releases 300K Turkey Government Emails In Response To Erdogan’s Post-Coup Purges
#:Web, Internet
::: Slashdot

CmDdopVXIAAujQK

Free Programming Books for Coders of All Levels
#:programming, codice, snippet
::: I am Programmer

Come richiedere un account verificato Twitter
non m’interessa ma chissà…
#:social media
::: Chimera Revo

Microsoft blocca l’installazione di altri OS su dispositivi Windows RT
#:sistemi operativi
::: lffl

Pokémon GO e la direzione del futuro
#:games
::: Sergio Gridelli

If you want to bootstrap a Lisp->Javascript compiler
#:lisp e derivati
::: davazp

Cn4Ao1gWYAE4KEf

pifpaf 0.10.0
Suite of tools and fixtures to manage daemons for testing
#:tools, componenti software
::: PyPI

#CurryOn Rome videos already rolling in on our YouTube channel
#:linguaggi di programmazione
::: curry_on_conf

Git Magic ebook
#:manuali, how to
::: Stanford CS

view the generated HTML source in Firefox
#:Web, Internet
::: The Ubuntu Incident

AT&T Hopes Open Source SDN Platform Will Become ‘Industry Standard’
#:free open source software
::: Virtualization Review

tumblr_oao1vyjOjS1qboyowo1_500

Gow – The lightweight alternative to Cygwin
Gow (Gnu On Windows) is the lightweight alternative to Cygwin
#:tools, componenti software
::: bmatzelle

Apple To Make $3 Billion From Pokemon Go
#:games
::: Slashdot

Stack Overflow goes beyond Q&As and launches crowdsourced documentation
::: TechCrunch

An Introduction to Recursion Schemes
#:programmazione funzionale
::: Adventures in Uncertainty ::: Adventures in Uncertainty ::: Adventures in Uncertainty

Using Golang For Custom Wallpapers
io avevo fatto una cosa simile con Python, anni fa
#prog
::: John Pettigrew

Practical Guide to Bare Metal C++
#:manuali, how to
::: Alex Robenko

13754169_10154449642060962_2726208975888981182_n

LLVM Programmer’s Manual
#:manuali, how to
::: LLVM

excited to announce Amazon artificial intelligence & machine learning center in Turin
#:ditte
::: JeffBezos ::: Business Insider

Racket v6.6 is out!
fatto😀
#:lisp e derivati
::: racketlang

Wrote and edited some documentation for Common #Lisp on Stackoverflow
#:lisp e derivati
::: RainerJoswig

A Formal Verification of Rust’s Binary Search Implementation
una cosa teorica, ostica, ottima😀
#:programming, codice, snippet
::: The Axiom of False

13th Intern. Congress on Mathematical Education in Hamburg. ‘USING #LISP AS A TOOL FOR MATHEMATICAL EXPERIMENTATION’
#:lisp e derivati
::: RainerJoswig

150850597-e4f5a94a-f27a-43de-b7a3-b2fbcf61d634

Coconut – operatori II

1892_5

Ci sono argomenti istituzionali come Octave (sì siamo in ritardo ma il caldo, le ferie, …) e ci sono argomenti che forse poi –chissà– come Coconut. Poi ce ne sono anche altri ancora, come SICP, che meriterebbero più attenzione. Avendo tempo. OK, oggi Coconut, continuo da qui a copiare qui.

Iterator Slicing
Coconut uses a $ sign right after an iterator before a slice to perform iterator slicing. Coconut’s iterator slicing works much the same as Python’s sequence slicing, and looks much the same as Coconut’s partial application, but with brackets instead of parentheses. It has the same precedence as subscription.
Iterator slicing works just like sequence slicing, including support for negative indices and slices, and support for slice objects in the same way as can be done with normal slicing. Iterator slicing makes no guarantee, however, that the original iterator passed to it be preserved (to preserve the iterator, use Coconut’s tee function).
Coconut’s iterator slicing is very similar to Python’s itertools.islice, but unlike itertools.islice, Coconut’s iterator slicing supports negative indices, and is optimized to play nicely with custom or built-in sequence types as well as Coconut’s map, zip, range, and count objects, only computing the elements of each that are actually necessary to extract the desired slice. This behavior can also be extended to custom objects if they define their __getitem__ method lazily and set __coconut_is_lazy__ to True.

c24

Nota: il manuale usa 10**100 ma mi da overflow😳

With Python can’t be done without a complicated iterator slicing function and inspection of custom objects. The necessary definitions in Python can be found in the Coconut header.

Alternative Unicode
Coconut supports Unicode alternatives to many different operator symbols. The Unicode alternatives are relatively straightforward, and chosen to reflect the look and/or meaning of the original symbol.

→ (\u2192)                  => "->"
↦ (\u21a6)                  => "|>"
*↦ (*\u21a6)                => "|*>"
↤ (\u21a4)                  => "<|" 
↤* (\u21a4*)                => "<*|" 
⋅ (\u22c5)                  => "*"
↑ (\u2191)                  => "**"
÷ (\xf7)                    => "/"
÷/ (\xf7/)                  => "//"
∘ (\u2218)                  => ".."
− (\u2212)                  => "-" (only subtraction)
⁻ (\u207b)                  => "-" (only negation)
¬ (\xac)                    => "~"
≠ (\u2260) or ¬= (\xac=)    => "!="
≤ (\u2264)                  => "<=" 
≥ (\u2265)                  => ">="
∧ (\u2227) or ∩ (\u2229)    => "&"
∨ (\u2228) or ∪ (\u222a)    => "|"
⊻ (\u22bb) or ⊕ (\u2295)    => "^"
« (\xab)                    => "<<" 
» (\xbb)                    => ">>"
… (\u2026)                  => "..."
× (\xd7)                    => "@" (only matrix multiplication)

c25

OK, ma forse –sono vecchio– perché cambiare. E poi non è comodissimo introdurre il codice dopo C-S-u. Non sono riuscito a usare quelli con il codice esadecimale, per esempio xf7.

Keywords

data
The syntax for data blocks is a cross between the syntax for functions and the syntax for classes. The first line looks like a function definition, but the rest of the body looks like a class, usually containing method definitions. This is because while data blocks actually end up as classes in Python, Coconut automatically creates a special, immutable constructor based on the given arguments.

Coconut data blocks create immutable classes derived from collections.namedtuple and made immutable with __slots__. Coconut data statement syntax looks like:

data <name>(<args>):
    <body>

<name> is the name of the new data type, <args> are the arguments to its constructor as well as the names of its attributes, and <body> contains the data type’s methods.Subclassing data types can be done easily by inheriting from them in a normal Python class, although to make the new subclass immutable, the line

__slots__ = ()

Rationale
A mainstay of functional programming that Coconut improves in Python is the use of values, or immutable data types. Immutable data can be very useful because it guarantees that once you have some data it won’t change, but in Python creating custom immutable data types is difficult. Coconut makes it very easy by providing data blocks.

Python Docs
Returns a new tuple subclass. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with type names and field names) and a helpful __repr__() method which lists the tuple contents in a name=value format.

Any valid Python identifier may be used for a field name except for names starting with an underscore. Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be a keyword such as class, for, return, global, pass, or raise.

Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.

c26

This will fail because data objects are immutable

c27

la versione Python

c28

Showcases the syntax, features, and immutable nature of data types.

c29

Nota: la riga dopo il decoratore viene scritta in modo bizzarro nella REPL, quella corretta è def size(Node(left, right)) = size(left) + size(right) ovviamente.

la versione Python

c30

Pausa, devo digerire il tutto; poi continuo sempre sulle keywords😀
:mrgreen:

Iscriviti

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

Segui assieme ad altri 93 follower