Coconut – operatori I

Chjgv5mUkAAZhoL

Continuo da qui l’esame di Coconut, qui.

Prima di tutto una nota che a me non interessa più di tanto ma chissà…

Supporto di IPython/Jupyter
If you prefer IPython (the python kernel for the Jupyter framework) to the normal Python shell, Coconut can be used as an IPython extension or Jupyter kernel.

Extension
If Coconut is used as an extension, a special magic command will send snippets of code to be evaluated using Coconut instead of IPython, but IPython will still be used as the default. The line magic %load_ext coconut will load Coconut as an extension, adding the %coconut and %%coconut magics. The %coconut line magic will run a line of Coconut with default parameters, and the %%coconut block magic will take command-line arguments on the first line, and run any Coconut code provided in the rest of the cell with those parameters.

Kernel
If Coconut is used as a kernel, all code in the console or notebook will be sent directly to Coconut instead of Python to be evaluated. The command coconut --jupyter notebook (or coconut --ipython notebook) will launch an IPython/Jupyter notebook using Coconut as the kernel and the command coconut --jupyter console (or coconut --ipython console) will launch an IPython/Jupyter console using Coconut as the kernel. Additionally, the command coconut --jupyter (or coconut --ipython) will add Coconut as a language option inside of all IPython/Jupyter notebooks, even those not launched with Coconut. This command may need to be re-run when a new version of Coconut is installed.

Operatori

Lambdas
Coconut provides the simple, clean -> operator as an alternative to Python’s lambda statements. The operator has the same precedence as the old statement.
In Python, lambdas are ugly and bulky, requiring the entire word lambda to be written out every time one is constructed. This is fine if in-line functions are very rarely needed, but in functional programming in-line functions are an essential tool.
Lambda forms (lambda expressions) have the same syntactic position as expressions. They are a shorthand to create anonymous functions; the expression (arguments) -> expression  yields a function object. The unnamed object behaves like a function object defined with:

def (arguments):
    return expression

Note that functions created with lambda forms cannot contain statements or annotations.

Esempio:

c18

Applicazione parziale (currying)
Partial application, or currying, is a mainstay of functional programming, and for good reason: it allows the dynamic customization of functions to fit the needs of where they are being used. Partial application allows a new function to be created out of an old function with some of its arguments pre-specified.

Python Docs
Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords. Roughly equivalent to:

def partial(func, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*(args + fargs), **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc

The partial object is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature.

Esempio:

c19

😳 un messaggio alieno 😉

Pipeline
Coconut uses pipe operators for pipeline-style function application. All the operators have a precedence in-between infix calls and comparisons and are left-associative. All operators also support in-place versions. The different operators are:
(|>)  => pipe forward
(|*>) => multiple-argument pipe forward
(<|)  => pipe backward
(<*|) => multiple-argument pipe backward

Esempio:

c20

Compose
Coconut uses the .. operator for function composition. It has a precedence in-between subscription and exponentiation. The in-place operator is ..=.

Esempio:

c21

Chain
Coconut uses the :: operator for iterator chaining. Coconut’s iterator chaining is done lazily, in that the arguments are not evaluated until they are needed. It has a precedence in-between bitwise or and infix calls. The in-place operator is ::=.
A useful tool to make working with iterators as easy as working with sequences is the ability to lazily combine multiple iterators together. This operation is called chain, and is equivalent to addition with sequences, except that nothing gets evaluated until it is needed.

Python Docs
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Chained inputs are evaluated lazily. Roughly equivalent to:

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

Esempio:
Can’t be done without a complicated iterator comprehension in place of the lazy chaining. See the compiled code for the Python syntax.

c22

Questo è il file conc.coco:

def N(n=0):
    return (0,) :: N(n+1) # no infinite loop because :: is lazy

(range(-10, 0) :: N())$[5:15] |> list |> print

compilo…

c23

295 righe non proprio leggibili, ecco le ulitime:

def N(n=0):
    return _coconut.itertools.chain.from_iterable((_coconut_lazy_item()
          for _coconut_lazy_item in (lambda: (0,), 
          lambda: N(n + 1)))) # no infinite loop because :: is lazy

(print)((list)(_coconut_igetitem(
          (_coconut.itertools.chain.from_iterable((_coconut_lazy_item() 
              for _coconut_lazy_item in (lambda: range(-10, 0), 
                    lambda: N())))), _coconut.slice(5, 15))))

Nota: ho spezzato le righe a sentimento per visualizzarle, troppo lunghe.

Pausa che devo riprendermi 😉
:mrgreen:

Posta un commento o usa questo indirizzo per il trackback.

Trackback

  • Coconut – operatori II | Ok, panico su 23 luglio 2016 alle 09:21

    […] ancora, come SICP, che meriterebbero più attenzione. Avendo tempo. OK, oggi Coconut, continuo da qui a copiare […]

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo di WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione /  Modifica )

Google photo

Stai commentando usando il tuo account Google. Chiudi sessione /  Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione /  Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione /  Modifica )

Connessione a %s...

Questo sito utilizza Akismet per ridurre lo spam. Scopri come vengono elaborati i dati derivati dai commenti.

%d blogger hanno fatto clic su Mi Piace per questo: