Racket – espressioni e definizioni – 3

bb12Oggi qui [doc]/guide/scheme-forms.html proseguendo da qui.

Definizioni: define

A basic definition has the form

(define id expr)

in which case id is bound to the result of expr.

ed17

The define form also supports a shorthand for function definitions:

(define (id arg ...) body ...+)

which is a shorthand for

(define id (lambda (arg ...) body ...+))

ed18

The function shorthand via define also supports a rest argument (i.e., a final argument to collect extra arguments in a list):

(define (id arg ... . rest-id) body ...+)

which is a shorthand

(define id (lambda (arg ... . rest-id) body ...+))

ed19

Adesso sono nei guai: non so tradurre curry, specie quando declinato come aggettivo, portate pazienza :roll:
Poi, ripensandoci, lascio in inglese, tanto c’è lo spiegone.

Curried functions

Consider the following make-add-suffix function that takes a string and returns another function that takes a string:

ed20

Although it’s not common, result of make-add-suffix could be called directly, like this:

ed21

In a sense, make-add-suffix is a function takes two arguments, but it takes them one at a time. A function that takes some of its arguments and returns a function to consume more is sometimes called a curried function.

Using the function-shorthand form of define, make-add-suffix can be written equivalently as

ed22

This shorthand reflects the shape of the function call (make-add-suffix "!"). The define form further supports a shorthand for defining curried functions that reflects nested function calls:

ed23

The full syntax of the function shorthand for define is as follows:

(define (head args) body ...+)
 
  head = id
       | (head args)
 	 	 	 	 
  args = arg ...
       | arg ... . rest-id

The expansion of this shorthand has one nested lambda form for each head in the definition, where the innermost head corresponds to the outermost lambda.

Valori multipli e define-values

A Racket expression normally produces a single result, but some expressions can produce multiple results. For example, quotient and remainder each produce a single value, but quotient/remainder produces the same two values at once:

ed24

As shown above, the REPL prints each result value on its own line.

Multiple-valued functions can be implemented in terms of the values function, which takes any number of values and returns them as the results:

ed25

The define-values form binds multiple identifiers at once to multiple results produced from a single expression:

(define-values (id ...) expr)

The number of results produced by the expr must match the number of ids.

ed26

A define form (that is not a function shorthand) is equivalent to a define-values form with a single id.

Definizioni interne

Qui entriamo in una cosa lispica che a prima vista sembra difficile ma è quello che rende pheego il Lisp (e derivati).

When the grammar for a syntactic form specifies body, then the corresponding form can be either a definition or an expression. A definition as a body is an internal definition.

Expressions and internal definitions in a body sequence can be mixed, as long as the last body is an expression.

For example, the syntax of lambda is

(lambda (f)                ; no definitions
  (printf "running\n")
  (f 0))
     
(lambda (f)                ; one definition
  (define (log-it what)
    (printf "~a\n" what))
      (log-it "running")
    (f 0)
    (log-it "done"))
     
(lambda (f n)              ; two definitions
  (define (call n)
    (if (zero? n)
        (log-it "done")
        (begin
          (log-it "running")
          (f n)
          (call (- n 1)))))
  (define (log-it what)
    (printf "~a\n" what))
  (call n))

so the following are valid instances of the grammar:

(lambda gen-formals
  body ...+)

Internal definitions in a particular body sequence are mutually recursive; that is, any definition can refer to any other definition—as long as the reference isn’t actually evaluated before its definition takes place. If a definition is referenced too early, an error occurs.

ed27

A sequence of internal definitions using just define is easily translated to an equivalent letrec form ([prossimamente]). However, other definition forms can appear as a body, including define-values, struct ([prossimamente]) or define-syntax ([macros]).

Pausa (ci vuole, imho) :mrgreen:

Racket – espressioni e definizioni – 2

41208_450Oggi qui: [doc]/guide/scheme-forms.html continuando da qui.

lambda

A lambda expression creates a function. In the simplest case, a lambda expression has the form

(lambda (arg-id ...)
  body ...+)

A lambda form with n arg-ids accepts n arguments:

ed8

Dichiarare un argomento rest

Ieri l’ho detto che me l’aspettavo :grin:
A lambda expression can also have the form

(lambda rest-id
  body ...+)

That is, a lambda expression can have a single rest-id that is not surrounded by parentheses. The resulting function accepts any number of arguments, and the arguments are put into a list bound to rest-id.

ed9

Functions with a rest-id often use apply to call another function that accepts any number of arguments.

ed10

The lambda form also supports required arguments combined with a rest-id:

(lambda (arg-id ...+ . rest-id)
  body ...+)

The result of this form is a function that requires at least as many arguments as arg-ids,  and also accepts any number of additional arguments.

ed11

A rest-id variable is sometimes called a rest argument, because it accepts the “rest” of the function arguments.
È simile ma non identico alla versione di CL.

Dichiarare argomenti opzionali

Instead of just an identifier, an argument (other than a rest argument) in a lambda form can be specified with an identifier and a default value:

(lambda gen-formals
  body ...+)
 
  gen-formals = (arg ...)
              | rest-id
 	      | (arg ...+ . rest-id)
 	 	 	 	 
         arg = arg-id
 	 [arg-id default-expr]

An argument of the form [arg-id default-expr] is optional. When the argument is not supplied in an application, default-expr produces the default value. The default-expr can refer to any preceding arg-id, and every following arg-id must have a default as well.

ed12

Anche qui sintassi diversa (migliore) rispetto CL.

Dichiarare keyword arguments

A lambda form can declare an argument to be passed by keyword, instead of position. Keyword arguments can be mixed with by-position arguments, and default-value expressions can be supplied for either kind of argument:

(lambda gen-formals
  body ...+)
 
  gen-formals =	(arg ...)
 	      | rest-id
 	      |	(arg ...+ . rest-id)
 	 	 	 	 
          arg = arg-id
 	      |	[arg-id default-expr]
 	      |	arg-keyword arg-id
 	      | arg-keyword [arg-id default-expr]

An argument specified as arg-keyword arg-id is supplied by an application using the same arg-keyword. The position of the keyword–identifier pair in the argument list does not matter for matching with arguments in an application, because it will be matched to an argument value by keyword instead of by position.

ed13

An arg-keyword [arg-id default-expr] argument specifies a keyword-based argument with a default value.

ed14

The lambda form does not directly support the creation of a function that accepts “rest” keywords. To construct a function that accepts all keyword arguments, use make-keyword-procedure. The function supplied to make-keyword-procedure receives keyword arguments through parallel lists in the first two (by-position) arguments, and then all by-position arguments from an application as the remaining by-position arguments.

ed15

OK, introdotto cose nuove di soppiatto ma è chiaro :wink:

Funzioni dipendenti dall’arità: case-lambda

The case-lambda form creates a function that can have completely different behaviors depending on the number of arguments that are supplied. A case-lambda expression has the form

(case-lambda
  [formals body ...+]
  ...)
      
  formals = (arg-id ...)
          | rest-id
          | (arg-id ...+ . rest-id)

where each [formals body ...+] is analogous to (lambda formals body ...+). Applying a function produced by case-lambda is like applying a lambda for the first case that matches the number of given arguments.

ed16

A case-lambda function cannot directly support optional or keyword arguments.

Nota perso: sì ho solo copiato; in fondo-in fondo è tutto logico e semplice; poi quando si tratterà di usarla si dovrà consultare la guida (questo post).

:mrgreen:

Spyder, un IDE per Python

Spyder_logo

Sapete la serendipity, ricorsiva in questo caso. Recentemente un giovane volonteroso mi chiedeva quale IDE semplice usare per impratichirsi con Python. Io, dopo avergli ricordato che essedo vecchio uso un editor normale (Gedit, sì lo so che c’è di meglio) ho consigliato Geany. Che ogni tanto uso anch’io. E sì, c’è anche per Windows, cosa che in quel caso era necessaria.
Giovedì pomeriggio mi viene ripetuta la stessa richiesta. E io insisto con Geany.

E adesso chi glielo dice ai due? Sì perché ho trovato di meglio, grazie a un post che raccomanda Emacs: Emacs for Data Science.

Ma non voglio propagandare Emacs. Anche se è il migliore in assoluto, senza paragoni. Solo che per imparare a usarlo e sfruttare le sue possibilità ci vuole tempo e costanza e poi forse per le cose piccole non è necessario :roll: (Dai non infierite, a volte lo uso, per esempio con SLIME).

Spyder (formerly Pydee) is an open source cross-platform IDE for scientific programming in the Python language. Spyder integrates NumPy, SciPy, Matplotlib and IPython, as well as other open source software, dice la Wiki.

Una rapida occhiata alla pagina degli screenshots mi ha convinto a provarlo.

Per Ubuntu c’è nel Software Center, installo (per la versione 2.x ma c’è anche per la 3), 51 MB, ed ecco:

click per ingrandire

click per ingrandire

Nel terminale (ma non sono più obbligato a usarlo, cosa che genera lamentele per i windowsiani) ottengo:

con-fib

OK, l’esempio è semplicissimo, questo è il codice (fib.py):

# -*- coding: utf-8 -*-

def fibGen(n, a=0, b=1):
    print a, b,
    while n > 0:
        yield a
        a, b, n = b, a+b, n - 1
        print b,
        if (n % 5) == 0: print
#main
[i for i in fibGen(50)]

Ovviamente c’è molto di più, conviene leggere la documentazione, qui: Spyder – Documentation.
Il sito di Spyder è su GitHub.
E sì, dice come installarlo su Windows :grin:

Visto nel Web – 193

Continua a fare caldo :sad: Ma io ci sono, ci sono novità in arrivo (forse, ma non subito). Intanto ecco cosa ho visto nel Web.
Linus
git commit -m “Fixed interface issues.”

::: jonathansampson

Waybacklapse 2.0: A Python Wayback Machine Time-Lapse Creator (Now with Python3 and Docker!)
::: Kyle Purdon

A historical note from the 1984 preface to “Lisp Machine Manual”
::: btbytes

Silenzi che valgono come risposte
::: Tech Economy

The Best Programming Language is None
::: Bitbucket

backup

Numerators of harmonic numbers
con Python si possono fare cose che voi umani…
::: The Endeavour

SPIEGEL Interview with WikiLeaks Head Julian Assange
::: _arianna

Today in irony: Paper titled “Promoting an open research culture”
::: abigailStev

VERY happy with the future default #matplotlib colormap
::: astrofrog

Twitter: a cosa servono i Preferiti?
::: Downloadblog

CKwvapxW8AEAgMH

Oracle rilascia VirtualBox 5
::: lffl

GCC 5.2 Released
io ho il 4.9.2, sono vecchio :wink:
::: Slashdot

Keep the dream alive
::: yurrriq

Spam drops below 50% of email for the first time since 2003
::: EmileTrombetti

Next Nobel Prize
::: keul

just-cooking

Big tech companies back Samsung in court case against Apple
::: Engadget

Monoid
Open Source Coding Font
::: larsenwork

Compare and contrast: Apple and Microsoft
::: The Economist

The Seven Stages of SVG
::: codepen

Come la Cina censura WeChat
::: Chiusi nella rete

9e6ab51002520133f0f4005056a9545d

A group of wolves is called a pack
::: SkylerFoxy

Hackers Remotely Kill a Jeep on the Highway
::: taosecurity

Free Tools For Detecting Hacking Team Malware In Your Systems
::: Slashdot

We need to go beyond the web
::: Daniel Lemire

Gmail Spam Filter Changes Bite Linus Torvalds
::: Slashdot

IMG_1388

Ma questa menata dei cookie
::: DarioBressanini

Keyword Bookmarks for OpenStack Developers
::: Doug Hellmann

The Risks of Regulating Zero-Days
::: The Center for Internet and Society

Instagram: cosa succede quando vi chiamate come un vip? La storia di Andres Iniesta
::: Downloadblog

A che gioco sta giocando Twitter in Turchia? Ubbidisce e basta?
::: fabiochiusi

beretta

Your Timeline: Revisiting the world that you’ve explored
uhmmm…
::: Google

The Anatomy of a Puzzle
A Case Study In “Specification Driven Programming”
::: chriskohlhepp

44 anni di UNIX
::: SIAMO GEEK

No, la colpa non è degli altri…
::: SIAMO GEEK

Mostly adequate guide to FP (in javascript)
This is a book on the functional paradigm in general
::: DrBoolean

lol-face-funny-meme

Page 2
::: flaviadok

the mockups for the virtual desktops implementation under Budgie desktop
::: Google+

Try Periscope
::: periscope

PyData Seattle 2015 Scikit-Learn Tutorial
::: nbviewer

Eight years of blogging. Over one million visitors
10 volte OKp, Peteris rockz! :grin:
::: Peteris Krumins

kepler-452b

Wi-Fi libero, ma…
::: SIAMO GEEK

Google Voice transcriptions will soon actually make sense
::: Engadget

La BCE: Twitter può predire l’andamento della Borsa
::: ZEUS News

Trenta OS: Il tempo delle Pere 2
::: Nerd Slider

Twitter should not be used for reporting complex things
::: glipari

editors

Verification handbook
::: Luca De Biase

mbeddr: an Extensible C-based Programming Language and IDE for Embedded Systems
::: Lambda the Ultimate

Jusqu’au dernier souffle
::: CommitStrip

@KimKardashian great idea!
::: jack

David Mertz – Functional Programming in Python
::: O’Reilly

1a

The only remaining barrier to entry for Linux
::: TechRepublic

How to install Linux on a PC with Secure Boot enabled
::: PCWorld

What is Nuitka – The TL;DR …
Nuitka is a Python compiler
c’è nel Softare center di ‘buntu, in settimana… probabilmente …forse … :wink:
::: Nuitka

top-gnu

Racket – espressioni e definizioni – 1

j5Oggi qui: [doc]/guide/scheme-forms.html, l’inizio di una sezione che provides more details on [definitions, procedure applications, conditionals, and so on], plus a few additional basic forms.

Una nota

This chapter (and the rest of the documentation) uses a slightly different notation than the character-based grammars of the Racket Essentials chapter. The grammar for a use of a syntactic form something is shown like this:

(something [id ...+] an-expr ...)

Dai, mica copio tutto, tanto è qui: [doc]/guide/syntax-notation.html.

Ma siccome sto parlando di convenzioni di scrittura ricordo che [doc] è questo:

ed0(sì ‘buntu ne approfitta per lamentarsi di Firefox).

Identificatori e collegamento

The context of an expression determines the meaning of identifiers that appear in the expression. Cioè per usare Racket iniziare con

#lang racket

Forms like define, lambda, and let associate a meaning with one or more identifiers; that is, they bind identifiers. The part of the program for which the binding applies is the scope of the binding. The set of bindings in effect for a given expression is the expression’s environment.

Non so se è corretto ma questi sono alcuni termini italiani che uso:

binding = collegamento;
scope = vita;
environment = ambiente;
shadowing = ombreggiamento (pessima lo so ma si usa(va)
            dire così), forse meglio nascondere;

Esempio:

ed1

the define is a binding of f, the lambda has a binding for x, and the let has a binding for y. The scope of the binding for f is the entire module; the scope of the x binding is (let ([y 5]) (+ x y)); and the scope of the y binding is just (+ x y). The environment of (+ x y) includes bindings for y, x, and f, as well as everything in racket.

A module-level define can bind only identifiers that are not already defined or required into the module. A local define or other binding forms, however, can give a new local binding for an identifier that already has a binding; such a binding shadows the existing binding.

ed2

Adesso una cosa da lisper, chissà…
Similarly, a module-level define can shadow a binding from the module’s language. For example, (define cons 1) in a racket module shadows the cons that is provided by racket. Intentionally shadowing a language binding is rarely a good idea—especially for widely used bindings like cons—but shadowing relieves a programmer from having to avoid every obscure binding that is provided by a language.

Even identifiers like define and lambda get their meanings from bindings, though they have transformer bindings (which means that they indicate syntactic forms) instead of value bindings. Since define has a transformer binding, the identifier define cannot be used by itself to get a value. However, the normal binding for define can be shadowed.

ed3

da matti! uh, lo dice anche la guida: Again, shadowing standard bindings in this way is rarely a good idea, but the possibility is an inherent part of Racket’s flexibility.

Chiamate a funzione

An expression of the form

(proc-expr arg-expr ...)

is a function call—also known as a procedure application—when proc-expr is not an identifier that is bound as a syntax transformer (such as if or define).

Ordine di valutazione e arità

A function call is evaluated by first evaluating the proc-expr and all arg-exprs in order (left to right). Then, if proc-expr produces a function that accepts as many arguments as supplied arg-exprs, the function is called. Otherwise, an exception is raised.

ed4

Some functions, such as cons, accept a fixed number of arguments. Some functions, such as + or list, accept any number of arguments. Some functions accept a range of argument counts; for example substring accepts either two or three arguments. A function’s arity is the number of arguments that it accepts.

Uh! due cose:

  • ecco finalmente definita l’arità, è il numero di argomenti che la funzione accetta;
  • sospetto che si parlerà in futuro di funzioni con numero variabile di argomenti (cosa normale in CL e nei linguaggi correnti).

Keyword Arguments

Some functions accept keyword arguments in addition to by-position arguments. For that case, an arg can be an arg-keyword arg-expr sequence instead of just a arg-expr:

(proc-expr arg ...)
 
arg = arg-expr
    | arg-keyword arg-expr

For example,

(go "super.rkt" #:mode 'fast)

calls the function bound to go with "super.rkt" as a by-position argument, and with 'fast as an argument associated with the #:mode keyword. A keyword is implicitly paired with the expression that follows it.

Since a keyword by itself is not an expression, then

(go "super.rkt" #:mode #:fast)  ;; error

is a syntax error. The #:mode keyword must be followed by an expression to produce an argument value, and #:fast is not an expression.

The order of keyword args determines the order in which arg-exprs are evaluated, but a function accepts keyword arguments independent of their position in the argument list. The above call to go can be equivalently written

(go #:mode 'fast "super.rkt")

La funzione apply

The syntax for function calls supports any number of arguments, but a specific call always specifies a fixed number of arguments [uhmmm, forse non c’è quella cosa di CL]. As a result, a function that takes a list of arguments cannot directly apply a function like + to all of the items in a list:

ed5

The apply function offers a way around this restriction. It takes a function and a list argument, and it applies the function to the values in the list:

ed6

As a convenience, the apply function accepts additional arguments between the function and the list. The additional arguments are effectively consed onto the argument list:

ed7

The apply function accepts keyword arguments, too, and it passes them along to the called function:

(apply go #:mode 'fast '("super.rkt"))
(apply go '("super.rkt") #:mode 'fast)

Keywords that are included in apply’s list argument do not count as keyword arguments for the called function; instead, all arguments in this list are treated as by-position arguments. To pass a list of keyword arguments to a function, use the keyword-apply function, which accepts a function to apply and three lists. The first two lists are in parallel, where the first list contains keywords (sorted by keyword<), and the second list contains a corresponding argument for each keyword. The third list contains by-position function arguments, as for apply.

(keyword-apply go
               '(#:mode)
               '(fast)
               '("super.rkt"))

E sì, su apply c’è parecchio da dire, anche gossip, con tanti vips, anche Alan Kay ma questa è una guida seria (anche se non seriosa) :mrgreen:

Racket – tipi di dati built-in – 5

FairchildPheonixContinuando da qui oggi sono qui: [doc]/guide/datatypes.html.

Hash tables

Sì, non so tradurre :cry:
A hash table implements a mapping from keys to values, where both keys and values can be arbitrary Racket values, and access and update to the table are normally constant-time operations. Keys are compared using equal?, eqv?, or eq?, depending on whether the hash table is created with make-hash, make-hasheqv, or make-hasheq.

d37

The hash, hasheqv, and hasheq functions create immutable hash tables from an initial set of keys and values, in which each value is provided as an argument after its key. Immutable hash tables can be extended with hash-set, which produces a new immutable hash table in constant time.

d38

A literal immutable hash table can be written as an expression by using #hash (for an equal?-based table), #hasheqv (for an eqv?-based table), or #hasheq (for an eq?-based table). A parenthesized sequence must immediately follow #hash, #hasheq, or #hasheqv, where each element is a dotted key–value pair. The #hash, etc. forms implicitly quote their key and value sub-forms.

d39

Both mutable and immutable hash tables print like immutable hash tables, using a quoted #hash, #hasheqv, or #hasheq form if all keys and values can be expressed with quote or using hash, hasheq, or hasheqv otherwise:

d40

A mutable hash table can optionally retain its keys weakly, so each mapping is retained only so long as the key is retained elsewhere.

d41

Beware that even a weak hash table retains its values strongly, as long as the corresponding key is accessible. This creates a catch-22 dependency when a value refers back to its key, so that the mapping is retained permanently. To break the cycle, map the key to an ephemeron that pairs the value with its key (in addition to the implicit pairing of the hash table).

Dove l’ephemeron è una cosa mysteryousa ma c’è l’help:

LOL :wink:

oops! :wink:

OOPS! no, occorre andare alla Reference, Ephemerons, qui: [doc]/reference/ephemerons.html.

d43

ecco l’ephemeron:

d44

Boxes

OK, fatto il plurale, tanto sto copiando :wink:

A box is like a single-element vector. It can print as a quoted #& followed by the printed form of the boxed value. A #& form can also be used as an expression, but since the resulting box is constant, it has practically no use.

d45

void e undefined

Some procedures or expression forms have no need for a result value. For example, the display procedure is called only for the side-effect of writing output. In such cases the result value is normally a special constant that prints as #<void>. When the result of an expression is simply #<void>, the REPL does not print anything.

The void procedure takes any number of arguments and returns #<void>. (That is, the identifier void is bound to a procedure that returns #<void>, instead of being bound directly to #<void>.)

d46

The undefined constant, which prints as #<undefined>, is sometimes used as the result of a reference whose value is not yet available. In previous versions of Racket (before version 6.1), referencing a local binding too early produced #<undefined>; too-early references now raise an exception, instead.

d47

OK, finito con i tipi di dati prossimamente espressioni e definizioni :mrgreen:

Racket – tipi di dati built-in – 4

tdrOggi, continuando da qui, sono qui: [doc]/guide/datatypes.html.

Coppie e liste

A pair joins two arbitrary values. The cons procedure constructs pairs, and the car and cdr procedures extract the first and second elements of the pair, respectively. The pair? predicate recognizes pairs. Già visto qualcosa, comunque:

d28

A list is a combination of pairs that creates a linked list. More precisely, a list is either the empty list null, or it is a pair whose first element is a list element and whose second element is a list. The list? predicate recognizes lists. The null? predicate recognizes the empty list.

d29

Adesso una cosa particolare, srcloc va studiata nell’help:

d30

sì, al solito Firefox si lamenta ma è OK :wink:

A list or pair prints using list or cons when one of its elements cannot be written as a quoted value. For example, a value constructed with srcloc cannot be written using quote, and it prints using srcloc:

d31

OK, capito niente, nada, zilch!
As shown in the last example, list* is used to abbreviate a series of conses that cannot be abbreviated using list.

The write and display functions print a pair or list without a leading ', cons, list, or list*. There is no difference between write and display for a pair or list, except as they apply to elements of the list:

d32

Among the most important predefined procedures on lists are those that iterate through the list’s elements:

d33

foldl, già incontrata ma se del caso c’è l’ottimo help.

Pairs are immutable (contrary to Lisp tradition), and pair? and list? recognize immutable pairs and lists, only. The mcons procedure creates a mutable pair, which works with set-mcar! and set-mcdr!, as well as mcar and mcdr. A mutable pair prints using mcons, while write and display print mutable pairs with { and }:

d34

Vettori (vectors)

A vector is a fixed-length array of arbitrary values. Unlike a list, a vector supports constant-time access and update of its elements.

A vector prints similar to a list—as a parenthesized sequence of its elements—but a vector is prefixed with # after ', or it uses vector if one of its elements cannot be expressed with quote.

For a vector as an expression, an optional length can be supplied. Also, a vector as an expression implicitly quotes the forms for its content, which means that identifiers and parenthesized forms in a vector constant represent symbols and lists.

d35

Like strings, a vector is either mutable or immutable, and vectors written directly as expressions are immutable.

Vectors can be converted to lists and vice versa via vector->list and list->vector; such conversions are particularly useful in combination with predefined procedures on lists. When allocating extra lists seems too expensive, consider using looping forms like for/fold, which recognize vectors as well as lists.

d36

Pausa, parecchie cose da vedere oggi :mrgreen:

Racket – tipi di dati built-in – 3

2Bornot2BOggi sono qui: [doc]/guide/datatypes.html continuando da qui.

Simboli

A symbol is an atomic value that prints like an identifier preceded with '. An expression that starts with ' and continues with an identifier produces a symbol value. Quindi la definizione è un po’ diversa dal CL (Common Lisp) ma è la stessa cosa, rappresentata diversamente.

d18

For any sequence of characters, exactly one corresponding symbol is interned; calling the string->symbol procedure, or reading a syntactic identifier, produces an interned symbol. Since interned symbols can be cheaply compared with eq? (and thus eqv? or equal?), they serve as a convenient values to use for tags and enumerations.

Symbols are case-sensitive. By using a #ci prefix or in other ways, the reader can be made to case-fold character sequences to arrive at a symbol, but the reader preserves case by default.
Anche qui cambia rispetto a CL.

d19

Any string […] can be supplied to string->symbol to obtain the corresponding symbol. For reader input, any character can appear directly in an identifier, except for whitespace and the following special characters:

( ) [ ] { } " , ' ` ; # | \

Actually, # is disallowed only at the beginning of a symbol, and then only if not followed by %; otherwise, # is allowed, too. Also, . by itself is not a symbol.

Whitespace or special characters can be included in an identifier by quoting them with | or \. These quoting mechanisms are used in the printed form of identifiers that contain special characters or that might otherwise look like numbers.

d20

Per scrivere il simbolo senza apice si usa write, l’equivalente a display per le stringhe:

d21

Ecco la differenza è quella, difatti

d22

The gensym and string->uninterned-symbol procedures generate fresh uninterned symbols that are not equal (according to eq?) to any previously interned or uninterned symbol. Uninterned symbols are useful as fresh tags that cannot be confused with any other value.

d23

Keywords

A keyword value is similar to a symbol, but its printed form is prefixed with #:.

d24

Il CL usa : invece di #:.

More precisely, a keyword is analogous to an identifier; in the same way that an identifier can be quoted to produce a symbol, a keyword can be quoted to produce a value. The same term “keyword” is used in both cases, but we sometimes use keyword value to refer more specifically to the result of a quote-keyword expression or of string->keyword. An unquoted keyword is not an expression, just as an unquoted identifier does not produce a symbol:

d25

Nota perso: bello l’help della REPL

d26

Despite their similarities, keywords are used in a different way than identifiers or symbols. Keywords are intended for use (unquoted) as special markers in argument lists and in certain syntactic forms. For run-time flags and enumerations, use symbols instead of keywords. The example below illustrates the distinct roles of keywords and symbols. Chi ha detto “plist“?

d27

Continua :mrgreen:

I linguaggi degli astronomi

jakeJake (rockz!) ha postato un tweet molto intrigante: Interesting writeup on software use in astronomy.

Jake è un prof ed è un attivo pythonista, il suo blog è altamente raccomandato: Pythonic Perambulations.

Lo trovate nel primo video qui: Scientific computing in Python, davvero über-bravo :grin:

useMa basta parlare di Jake, l’argomento del post è il papero di Ivelina Momcheva e Erik Tollerud: Software Use in Astronomy: an Informal Survey.

The survey was carried out between December 2014 and February 2015, collecting responses from 1142 astronomers, spanning all career levels. We find that all participants use software in their research. The vast majority of participants, 90%, write at least some of their own software. Even though writing software is so wide-spread among the survey participants, only 8% of them report that they have received substantial training in software development. Another 49% of the participants have received “little” training. The remaining 43% have received no training. We also find that astronomers’ software stack is fairly narrow.

ikeaQuali sono i linguaggi più usati? The 10 most popular tools among astronomers are (from most to least popular): Python, shell scripting, IDL, C/C++, Fortran, IRAF, spreadsheets, HTML/CSS, SQL and Supermongo.

click per ingrandire

Uh! interessante, secondo me. Anche perché ci sono affinità con altre branche scientifiche (non necessariamente universitarie e di ricerca, penso all’ingegneria).
Python vince alla grande, il C/C++ è popolare ma c’è parecchio Fortran, quello che i giovani non vogliono sentir nominare. Ci sono anche altre cose, in particolare due tools ad hoc IDL e IRAF.

Una figura dal papero, con questa didascalia: Responses to the prompt “Select any of these that you regularly use in your research”, sub-divided by career stage. The options listed included: IDL, IRAF, Python, C, Fortran, Perl, Javascript, Julia, Matlab, Java, R, SQL, Shell Scripting, STAN, Figaro, Ruby, HML/CSS, Supermongo (labeled “sm”), and Excel or other spreadsheets (labeled “excel”). Respondents could add additional tools not listed using an “Other” box. Among the tools in this plot, four items were added by respondents: C++, Mathematica, gnuplot and awk. Note that the x axis varies between panels.

Notare che C++ sia stato aggiunto dai rispondenti, come anche Mathematica, Gnuplot e AWK.
Ci sono i fogli di calcolo (“excel”), Matlab (piace anche agli ing. di cui dicevo). Gnuplot io l’ho usato per visualizzare grafici da programmi Fortran (ne ho parlato anche nel blog) anche se non ha fatto innamorare nessuno, anzi…
Manca il Basic, Java è usato poco (chissà perché?). E sì manca il Lisp :cry: come pure tutti i nuovi linguaggi funzionali che hanno invaso la mia lista dei followati su Twitter.
Sarebbe bello apere cosa usano gli altri, per esempi i fisici; oltre a C++ ovviamente. Chissà…

Racket – tipi di dati built-in – 2

c1Continuo da qui a copiare qui: [doc]/guide/datatypes.html

Stringhe

Come già detto le stringhe sono Unicode, quasi: it’s an approximation that works well for many purposes. For example, any accented Roman letter can be represented as a scalar value, as can any common Chinese character.

A string is a fixed-length array of characters. It prints using doublequotes, where doublequote and backslash characters within the string are escaped with backslashes. Other common string escapes are supported, including \n for a linefeed, \r for a carriage return, octal escapes using \ followed by up to three octal digits, and hexadecimal escapes with \u (up to four digits). Unprintable characters in a string are normally shown with \u when the string is printed. Proprio come in C e linguaggi simili.

The display procedure directly writes the characters of a string […], in contrast to the string-constant syntax used to print a string result.

d11

Adesso una cosa che non ti aspetti, vero pythonisti?
A string can be mutable or immutable; strings written directly as expressions are immutable, but most other strings are mutable. The make-string procedure creates a mutable string given a length and optional fill character. The string-ref procedure accesses a character from a string (with 0-based indexing); the string-set! procedure changes a character in a mutable string.

d12

String ordering and case operations are generally locale-independent; that is, they work the same for all users. A few locale-dependent operations are provided that allow the way that strings are case-folded and sorted to depend on the end-user’s locale.

d13

Per locale è la solita solita storia di C et al. :roll:
For working with plain ASCII, working with raw bytes, or encoding/decoding Unicode strings as bytes, use byte strings.

Bytes e stringhe di bytes

A byte is an exact integer between 0 and 255, inclusive. The byte? predicate recognizes numbers that represent bytes.

d14

A byte string is similar to a string […] but its content is a sequence of bytes instead of characters. Byte strings can be used in applications that process pure ASCII instead of Unicode text. The printed form of a byte string supports such uses in particular, because a byte string prints like the ASCII decoding of the byte string, but prefixed with a #. Unprintable ASCII characters or non-ASCII bytes in the byte string are written with octal notation.

d15

The display form of a byte string writes its raw bytes […] Technically, display of a normal (i.e,. character) string prints the UTF-8 encoding of the string to the current output port, since output is ultimately defined in terms of bytes; display of a byte string, however, writes the raw bytes with no encoding. Along the same lines, when this documentation shows output, it technically shows the UTF-8-decoded form of the output.

d16

Non so se possa servire ma c’è: For explicitly converting between strings and byte strings, Racket supports three kinds of encodings directly: UTF-8, Latin-1, and the current locale’s encoding. General facilities for byte-to-byte conversions (especially to and from UTF-8) fill the gap to support arbitrary string encodings.

d17

Pausa :mrgreen:

Iscriviti

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

Unisciti agli altri 88 follower