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:

Racket – tipi di dati built-in – 1

TOggi qui: [doc]/guide/datatypes.html.

Inizio a esaminare in modo dettagliato i tipi di dati già visti; c’è qualcosa di diverso dai soliti linguaggi derivati da Algol (e dal Fortran).

Booleani

Racket has two distinguished constants to represent boolean values: #t for true and #f for false. Uppercase #T and #F are parsed as the same values, but the lowercase forms are preferred.

The boolean? procedure recognizes the two boolean constants. In the result of a test expression for if, cond, and, or, etc., however, any value other than #f counts as true.

Numeri

A Racket number is either exact or inexact:

An exact number is either

  • an arbitrarily large or small integer, such as 5, 99999999999999999, or -17;
    a rational that is exactly the ratio of two arbitrarily small or large integers, such as 1/2, 99999999999999999/2, or -3/4; or
  • a complex number with exact real and imaginary parts (where the imaginary part is not zero), such as 1+2i or 1/2+3/4i.

An inexact number is either

  • an IEEE floating-point representation of a number, such as 2.0 or 3.14e+87, where the IEEE infinities and not-a-number are written +inf.0, -inf.0, and +nan.0 (or -nan.0); or
  • a complex number with real and imaginary parts that are IEEE floating-point representations, such as 2.0+3.0i or -inf.0+nan.0i; as a special case, an inexact complex number can have an exact zero real part with an inexact imaginary part.

Inexact numbers print with a decimal point or exponent specifier, and exact numbers print as integers and fractions. The same conventions apply for reading number constants, but #e or #i can prefix a number to force its parsing as an exact or inexact number. The prefixes #b, #o, and #x specify binary, octal, and hexadecimal interpretation of digits.

d0

Computations that involve an inexact number produce inexact results, so that inexactness acts as a kind of taint on numbers. Beware, however, that Racket offers no “inexact booleans,” so computations that branch on the comparison of inexact numbers can nevertheless produce exact results. The procedures exact->inexact and inexact->exact convert between the two types of numbers.

d1

Quando possibile Racket usa valori interi:

d2

In terms of performance, computations with small integers are typically the fastest, where “small” means that the number fits into one bit less than the machine’s word-sized representation for signed numbers. Computation with very large exact integers or with non-integer exact numbers can be much more expensive than computation with inexact numbers.

d3

The number categories integer, rational, real (always rational), and complex are defined in the usual way, and are recognized by the procedures integer?, rational?, real?, and complex?, in addition to the generic number?. A few mathematical procedures accept only real numbers, but most implement standard extensions to complex numbers.

d4

The = procedure compares numbers for numerical equality. If it is given both inexact and exact numbers to compare, it essentially converts the inexact numbers to exact before comparing. The eqv? (and therefore equal?) procedure, in contrast, compares numbers considering both exactness and numerical equality.

d5

Beware of comparisons involving inexact numbers, which by their nature can have surprising behavior. Even apparently simple inexact numbers may not mean what you think they mean; for example, while a base-2 IEEE floating-point number can represent 1/2 exactly, it can only approximate 1/10:

d6

Caratteri (characters)

A Racket character corresponds to a Unicode scalar value.
[A]ny accented Roman letter can be represented as a scalar value, as can any common Chinese character.

Although each Racket character corresponds to an integer, the character datatype is separate from numbers. The char->integer and integer->char procedures convert between scalar-value numbers and the corresponding character.

A printable character normally prints as #\ followed by the represented character. An unprintable character normally prints as #\u followed by the scalar value as hexadecimal number. A few characters are printed specially; for example, the space and linefeed characters print as #\space and #\newline, respectively.

d7

The display procedure directly writes a character to the current output port (see Input and Output, prossimamente), in contrast to the character-constant syntax used to print a character result.

d8

Racket provides several classification and conversion procedures on characters. Beware, however, that conversions on some Unicode characters work as a human would expect only when they are in a string (e.g., upcasing “ß” or downcasing “Σ”).

d9

The char=? procedure compares two or more characters, and char-ci=? compares characters ignoring case. The eqv? and equal? procedures behave the same as char=? on characters; use char=? when you want to more specifically declare that the values being compared are characters.

d10

Pausa, ma poi continua, prossimamente :grin: e sì, praticamente ho solo copiato :roll:

:mrgreen:

Visto nel Web – 192

L’ho già detto fa caldo? Se no ve lo dico adesso: fa caldo, tanto, troppo. Ma questione di qualche mese e passa, probabilmente, forse. Intanto ecco cosa ho visto nel Web.
ant-chiptaking a screenshot about a webpage
::: The Ubuntu Incident

Microsoft: al Comune di Pesaro i conti non tornano
::: Tech Economy ::: Tech Economy

/etc/init.d/daemon stop
::: Manz

1 Million Android Users were infected by Gaming Apps
::: securityaffairs

@Corriereit dovrebbe abbandonare per manifesta inferiorità
::: zacchiro

CJOt6ivWsAAq1t7

I worked at #HackingTeam, my emails were leaked to WikiLeaks and I’m ok with that
::: Medium

Laura Poitras Sues U.S. Government to Find Out Why She Was Repeatedly Stopped at the Border
::: The Intercept ::: The Intercept

Ci ha battuti il pesce rosso!
Sergio è da (ahemmm) followare :oops:
::: Sergio Gridelli

Smettete di usare Flash ADESSO
::: SIAMO GEEK

Altruimeritocrazia
eh…
::: MadBob

11692563_728428913934951_1402818249037376501_n

Functional Programming: Links, News And Resources (4)
::: Angel \”Java\” Lopez

Hacking Team, “perché è giusto pubblicare tutto”
::: Chiusi nella rete

A wish list
::: David R. MacIver

5 key takeaways about Twitter, Facebook and news use
::: Pew Research ::: Pew Internet

Turing e Template
::: GNUrants

11350872_10207200071265413_6265207273909555054_n

Planet Labs Has Launched Over 100 Imaging Satellites with Many More to Come (Video)
::: Slashdot

Five things I learned from Microsoft CEO Satya Nadella
per adesso lo vedo come un Renzi
::: ZDNet

Chi ha inventato l’MP3?
::: Facebook

HackingTeam: giocare coi fiammiferi in una tinozza di benzina
::: Le Scienze

Programmatic access to the call stack in C++
::: Eli Bendersky

Software field has evolved
::: venkat_s

11403499_10155856550725249_7818785972756123991_n

Why a Chinese Buyout of Micron Is Not Likely To Succeed
prima o poi…
::: Slashdot

Sbaglio o nemmeno lo scandalo #HackingTeam
::: fabiochiusi

Introducing Belle
::: Belle

Turning a Chromebook into a clojurebook
::: Clojure Geek

Company plans to turn NYC’s trash cans into WiFi hotspots
::: Engadget

11705334_10153745185591840_4357188545611753974_n

The Web We Have to Save
bello ma troppo lungo
::: Medium

sysdis -Universal System Visibility With Native Container Support
segnalato da Alexintosh
::: sysdis

Italian Linux Society lancia un crowdfunding per il software libero
::: LibreItalia

Sandals
A TkInter wrapper for python inspired by the GUI library Shoes for Ruby
::: georgewalton

PDF becomes 4th most popular religion
::: axelk

11667479_10205233170526215_2198170269718110432_n

Scientific computing in Python
::: The Endeavour

Interesting writeup on software use in astronomy
::: jakevdp

After Moore’s Law: how phones are becoming open-source
::: Wired

The rise and rise of Amazon
::: EconBizFin

Put #Haskell on your resume even if you don’t know it
::: LeviNotik

plutox3

Pyxley: Python Powered Dashboards
::: Multithreaded

Apple and Samsung may help make the SIM card disappear
::: The Verge

This guy gave the world his Facebook password and it took days for Facebook to intervene
::: Business Insider

MIPS goes to Pluto
::: Imagination

ODF 1.2 now an #ISO standard
::: tdforg

tumblr_nr2pk4Cbzi1tmgvq1o1_540

Government surveillance law is unlawful, High Court rules
::: svaroschi

Scala 2.12.0-M2 is now available!
::: Scala

Shashlik: nuovo emulatore Android sui Pc con Linux
::: oneOpenSource

Libertà di innovare! La vittoria della net neutrality in Europa è una buona notizia
::: Luca De Biase

When you write machine-code by hand
::: Google+

11705316_10207053054234847_1861241476507725379_n

miniMAL
a Clojure inspired Lisp implemented in less than 1024 bytes of JavaScript
::: kanaka

Wolfram obeys Zawinksi’s law
::: The Endeavour

Going beyond our limitations
::: Daniel Lemire

A Simplified EU Cookie Law Approach
non ancora provato, prossimamente…
::: Web Reflection

Alberto Cane

Alberto Cane

DrBoolean / mostly-adequate-guide
This is a book on the functional paradigm in general. We’ll use the world’s most popular functional programming language: JavaScript
::: DrBoolean

PureScript by Example
Functional Programming for the Web
::: Leanpub

Vittoria in Italia: il tribunale di Roma si pronuncia a favore della Fondazione Wikimedia
::: Wikimedia

rasterio 0.25.0
Fast and direct raster I/O for use with Numpy and SciPy
::: PyPI

How To Create A Tiny Wifi File-Sharing Beacon
::: N O D E

11053531_990625970982482_6657906981139373082_n

Why Aren’t Supercomputers Getting Faster Like They Used To?
::: IEEE Spectrum

BetterCap
BetterCap is an attempt to create a complete, modular, portable and easily extensible MITM framework with every kind of features could be needed while performing a man in the middle attack.
::: evilsocket

Punctuated equilibrium in the large scale evolution of programming languages
::: Lambda the Ultimate
11403094_323564004480808_969589248725805152_n

Racket – Coppie, liste e la sintassi di Racket

j9Oggi sono qui: [doc]/guide/Pairs__Lists__and_Racket_Syntax.html

Coppie puntate — pairs

The cons function actually accepts any two values, not just a list for the second argument. When the second argument is not empty and not itself produced by cons, the result prints in a special way. The two values joined with cons are printed between parentheses, but with a dot (i.e., a period surrounded by whitespace) in between:

p0

Thus, a value produced by cons is not always a list. In general, the result of cons is a pair. The more traditional name for the cons? function is pair?, and we’ll use the traditional name from now on.

E poi adesso arriva una cosa vecchia…
The name rest also makes less sense for non-list pairs; the more traditional names for first and rest are car and cdr, respectively. (Granted, the traditional names are also nonsense. Just remember that “a” comes before “d,” and cdr is pronounced “could-er.”)

p1

Ma è solo la tradizione…
Racket’s pair datatype and its relation to lists is essentially a historical curiosity, along with the dot notation for printing and the funny names car and cdr. Pairs are deeply wired into to the culture, specification, and implementation of Racket, however, so they survive in the language.

Anzi no, [n]on-list pairs are used intentionally, sometimes. For example, the make-hash function takes a list of pairs, where the car of each pair is a key and the cdr is an arbitrary value.

The only thing more confusing to new Racketeers than non-list pairs is the printing convention for pairs where the second element is a pair, but is not a list:

p2

In general, the rule for printing a pair is as follows: use the dot notation unless the dot is immediately followed by an open parenthesis. In that case, remove the dot, the open parenthesis, and the matching close parenthesis.

p3

Quotare coppie e simboli con quote

A list prints with a quote mark before it, but if an element of a list is itself a list, then no quote mark is printed for the inner list:

p4

quote fa la stessa cosa

p5

e poi…

p6

A value that prints like a quoted identifier is a symbol. In the same way that parenthesized output should not be confused with expressions, a printed symbol should not be confused with an identifier. In particular, the symbol (quote map) has nothing to do with the map identifier or the predefined function that is bound to map, except that the symbol and the identifier happen to be made up of the same letters.

Indeed, the intrinsic value of a symbol is nothing more than its character content. In this sense, symbols and strings are almost the same thing, and the main difference is how they print. The functions symbol->string and string->symbol convert between them.

p7

Nota perso: non esiste function? ma procedure?:

p8

Altri casi:

p9

Abbreviare quote con '

As you may have guessed, you can abbreviate a use of quote by just putting ' in front of a form to quote:

p10

Adesso un pasticcio: A ' expands to a quote form in quite a literal way. You can see this if you put a ' in front of a form that has a ':

p11

The ' abbreviation works in output as well as input. The REPL’s printer recognizes the symbol 'quote as the first element of a two-element list when printing output, in which case it uses ' to print the output:

p12

Le liste e la sintassi di Racket

Now that you know the truth about pairs and lists, and now that you’ve seen quote, you’re ready to understand the main way in which we have been simplifying Racket’s true syntax.

The syntax of Racket is not defined directly in terms of character streams. Instead, the syntax is determined by two layers:

  • a reader layer, which turns a sequence of characters into lists, symbols, and other constants; and
  • an expander layer, which processes the lists, symbols, and other constants to parse them as an expression.

The rules for printing and reading go together. For example, a list is printed with parentheses, and reading a pair of parentheses produces a list. Similarly, a non-list pair is printed with the dot notation, and a dot on input effectively runs the dot-notation rules in reverse to obtain a pair.

Come coseguenza si può scrivere:

p13

ovvio, equivale a (+ 1 2). It is practically never a good idea to write application expressions using this dot notation; it’s just a consequence of the way Racket’s syntax is defined.

Uh!: Normally, . is allowed by the reader only with a parenthesized sequence, and only before the last element of the sequence. However, a pair of .s can also appear around a single element in a parenthesized sequence, as long as the element is not first or last. Such a pair triggers a reader conversion that moves the element between .s to the front of the list. The conversion enables a kind of general infix notation:

p14

This two-dot convention is non-traditional, and it has essentially nothing to do with the dot notation for non-list pairs. Racket programmers use the infix convention sparingly—mostly for asymmetric binary operators such as < and is-a?.

Nota perso: quasi tutto OK ma con qualche quirk che chissà… :wink:

:mrgreen:

Racket – liste, iterazioni e ricorsività – 2

dont-panic-2d879147e99656e23e108373e2b75f380Continuo da qui a copiare [doc]/guide/Lists__Iteration__and_Recursion.html#(part._tail-recursion)

Tail recursion

Both the my-length and my-map functions [del post precedente] run in O(n) time for a list of length n. Ecco cosa capita per (my-length (list "a" "b" "c")):

(my-length (list "a" "b" "c"))
= (+ 1 (my-length (list "b" "c")))
= (+ 1 (+ 1 (my-length (list "c"))))
= (+ 1 (+ 1 (+ 1 (my-length (list)))))
= (+ 1 (+ 1 (+ 1 0)))
= (+ 1 (+ 1 1))
= (+ 1 2)
= 3

You can avoid piling up additions by adding along the way. To accumulate a length this way, we need a function that takes both a list and the length of the list seen so far; the code below uses a local function iter that accumulates the length in an argument len:

l11

che viene valutata così:

(my-length (list "a" "b" "c"))
= (iter (list "a" "b" "c") 0)
= (iter (list "b" "c") 1)
= (iter (list "c") 2)
= (iter (list) 3)
3

The revised my-length runs in constant space, just as the evaluation steps above suggest. That is, when the result of a function call, like (iter (list "b" "c") 1), is exactly the result of some other function call, like (iter (list "c") 2), then the first one doesn’t have to wait around for the second one, because that takes up space for no good reason.

This evaluation behavior is sometimes called tail-call optimization, but it’s not merely an “optimization” in Racket; it’s a guarantee about the way the code will run. More precisely, an expression in tail position with respect to another expression does not take extra computation space over the other expression.

In the case of my-map, O(n) space complexity is reasonable, since it has to generate a result of size O(n). Nevertheless, you can reduce the constant factor by accumulating the result list. The only catch is that the accumulated list will be backwards, so you’ll have to reverse it at the very end:

l12

Però aspetta, se avessimo già visto for/list si potrebbe scrivere:

l13

then the for/list form in the function is expanded to essentially the same code as the iter local definition and use. The difference is merely syntactic convenience.

Ricorsività contro iterazione

Solito discorso, esaurimento dello stack:
The my-length and my-map examples demonstrate that iteration is just a special case of recursion. In many languages, it’s important to try to fit as many computations as possible into iteration form. Otherwise, performance will be bad, and moderately large inputs can lead to stack overflow. Similarly, in Racket, it is sometimes important to make sure that tail recursion is used to avoid O(n) space consumption when the computation is easily performed in constant space.

Ma pare che Racket si comporti particolarmente bene, you can run out of memory if a computation involves too much context, but exhausting memory typically requires orders of magnitude deeper recursion than would trigger a stack overflow in other languages. These considerations, combined with the fact that tail-recursive programs automatically run the same as a loop, lead Racket programmers to embrace recursive forms rather than avoid them. :grin:

Suppose, for example, that you want to remove consecutive duplicates from a list. While such a function can be written as a loop that remembers the previous element for each iteration, a Racket programmer would more likely just write the following:

l14

Quasi semplice, anzi potrebbe sostituire uniq :wink:

l15

:mrgreen:

Numeri grossi, chi mi aiuta? OOPS! no, capito!

gregUn post trovato on-teh-toobz, intrigante, questo: Made to Order.

L’autore sembra affidabile: My name is Greg Ross. I spent 25 years as an editorial manager in science, engineering, and education publishing, most recently at IEEE, UNext.com, the National Educational Service, and American Scientist magazine.

Lo verifico mi son detto prima di subito :grin:
Con Linux gli strumenti non mancano, per esempio bc un tool di sistema e calc, da installare, c’è tutto qui ma anche nel Software Center di Ubuntu.

OK, provo, ecco cosa ottengo con bc:

bc-err
NO! non va, Ok, panico! :evil:

La stessa cosa precisa-precisa capita con calc.
E allora comincio il post, titolandolo con la prima parte del titolo attuale.
E preparo un ritaglio dell’immagine del post di Greg e mentre sto GIMPando (croppando ed evidenziando) eccolo! salta fuori, l’8.
Quelli che leggono Terry Pratchett diranno come me che c’era da espettarselo. Loro e tutti gli altri diranno che bisogna sempre fare attenzione ai particolari, molta, molitissima attenzione :roll:

In ogni caso funziona, ecco bc:

bce calc:

calc
Ci sarebbe anche Python, in particolare il modulo mpmath. Anticamente gli avevo dedicato un post, roba del 12.

Ma devo rivederlo. E mi sa che avendo raggiunto il mio obiettivo lo metterò tra le cose urgenti ma non particolarmente urgentissimissime. Chissà… :mrgreen:

Racket – liste, iterazioni e ricorsività – 1

super_chickenOggi sono qui: [doc]/guide/Lists__Iteration__and_Recursion.html. Racket is a dialect of the language Lisp, whose name originally stood for “LISt Processor.” The built-in list datatype remains a prominent feature of the language. The list function takes any number of values and returns a list containing the values: l0 In addition to simple operations like append, Racket includes functions that iterate over the elements of a list. These iteration functions play a role similar to for in Java, Racket, [probabilmente Python] and other languages. The body of a Racket iteration is packaged into a function to be applied to each element, so the lambda form becomes particularly handy in combination with iteration functions. Different list-iteration functions combine iteration results in different ways. The map function uses the per-element results to create a new list: l1 The andmap and ormap functions combine the results by anding or oring: l2 The filter function keeps elements for which the body result is true, and discards elements for which it is #f: l3 Fin qua tutto tranquillo ma pronti per il passo successivo… The map, andmap, ormap, and filter functions can all handle multiple lists, instead of just a single list. The lists must all have the same length, and the given function must accept one argument for each list: l4 The foldl function generalizes some iteration functions. It uses the per-element function to both process an element and combine it with the “current” value, so the per-element function takes an extra first argument. Also, a starting “current” value must be provided before the lists: l5 Uh! però è risaputo: Despite its generality, foldl is not as popular as the other functions. One reason is that map, ormap, andmap, and filter cover the most common kinds of list loops. Racket provides a general list comprehension form for/list, which builds a list by iterating through sequences. Ma di questo se ne parlerà un’altra volta.

Iterazioni base di liste

Difficile tradurre “from scratch”, “da zero”? o come? :oops: Although map and other iteration functions are predefined, they are not primitive in any interesting sense. You can write equivalent iterations using a handful of list primitives. Since a Racket list is a linked list, the two core operations on a non-empty list are:

  • first: get the first thing in the list;
  • rest: get the rest of the list.

l6 To create a new node for a linked list—that is, to add to the front of the list—use the cons function, which is short for “construct.” To get an empty list to start with, use the empty constant: l7 Ovviamente c’è la funzione list se si sa a priori cosa metterci dentro: l8 To process a list, you need to be able to distinguish empty lists from non-empty lists, because first and rest work only on non-empty lists. The empty? function detects empty lists, and cons? detects non-empty lists: l9 Con queste possiamo definire la nostra versione delle funzioni length e map: l10 Poi una frase di quelle che mi piacciono: If the derivation of the above definitions is mysterious to you, consider reading How to Design Programs. If you are merely suspicious of the use of recursive calls instead of a looping construct, then read on. Sì la documentazione di Racket è eccezionale :grin: Pausa :mrgreen:

Racket – REPL e XREPL – 2

j4Continuo l’esame di REPL + XREPL, proseguendo da qui, utilizzando la documentazione in locale, questa: [doc]/xrepl/index.html.

Per inserire codice occorre un editor, DrRacket è ottimo e si può lanciare dalla REPL, anzi è una delle opzioni previste: ,dr ,drr ,drracket.

Runs DrRacket with the specified file/s. If no files are given, and the REPL is currently inside a module, the file for that module is used.

DrRacket is launched directly, without starting a new subprocess, and it is then kept running in a hidden window so further invocations are immediate. (When this command is used for the first time, you will see DrRacket start as usual, and then its window will disappear — that window is keeping DrRacket ready for quick editing.)

Si possono usare anche -new e -open. Provo:

x6

sembra tutto OK, adesso modifico il file, salvo e lo carico nella REPL

x7

Funziona, modifico ancora:

x8

devo avere il modulo corrente:

OK, chissà se un’ulteriore modifica (salvata) … No.

x9

Provo a chiudere DrRacket e riaprirlo con il modulo caricato nella REPL:

x10

OK, lo apre corretto, ma esegue la versione vecchia, provo a salvare… No, devo ricaricarlo:

x11

Quindi funziona con questi accorgimenti, tiene il nome ma ricaricarlo dopo ogni modifica salvata. Ovviamente vale anche se c’è il “main”.

#!/usr/bin/racket
#lang racket
(define (h-w)
  (println "Hello world!")
  (println "Ciao Juhan!!!"))
;; main
(h-w)

x12

OK, salvo imprevisti questa è la via :mrgreen:

Iscriviti

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

Unisciti agli altri 88 follower