Visto nel Web – 222

Continuano le prove per i tag delle categorie, chissà…
Intanto ecco cosa ho visto nel Web.

bagna
Windows 10
#:umorismo
::: The Bouletcorp

Tre Amici al Bar
#:free open source software #:hardware #:programming, codice, snippet
::: MadBob

US government jet lay in wait for Snowden in Copenhagen
#:sicurezza, spionaggio
::: the Guardian

ASCIIMATICS
Asciimatics is a package to help people create full-screen ASCII animations on any platform
#:programming, codice, snippet
::: peterbrittain

‘Appocalypse,’ Or How I Learned To Stop Worrying And Love AI
anche se ultimamente ho dei dubbi su TechCrunch
#:innovazioni, futuro #:programming, codice, snippet
::: TechCrunch

step-ladder-52290

The fight for a third-best smartphone OS has been lost. By everyone
#:sistemi operativi #:dispositivi mobili
::: Ars Technica

Ubuntu Linux in the Wild: How a French University Uses Unity
ah! ma allora non è solo qui che nessuno conosce Linux! :roll:
#:sistemi operativi
::: The VAR Guy

Microsoft Pyjion boosts Python speed
prossimamente anche per Linux, forse
#:programming, codice, snippet
::: InfoWorld

Marco Patuano, #TimNewBrand e le bestialità sull’#opendata a pagamento: punti di vista?
#:ditte #:dati, raccolta #:free open source software
::: Tech Economy

Come velocizzare Android: consigli pratici
non uso quelle robe ma chissà…
#:dispositivi mobili
::: bufferOverflow

12661950_10205807812849914_7266161441573422986_n

Twitter Beefs Are Now Front Page News in The Boston Globe
i tempi stanno cambiando; anche i vecchi media se ne accorgono
#:social media
::: Wired

laze
un modulo Python che –OK, vedetelo di là :wink:
#:programming, codice, snippet
::: boramalper

Giornalisti, blogger, barbieri e portinaie
#:Web, Internet
::: manteblog

Report: Google Will Go In Big For VR Hardware This Year
#:innovazioni, futuro #:ditte
::: Slashdot

MapReduce is not functional programming
#:algoritmi, codice
::: Medium

meteorite_autista_indiano

Video Gamers From the ’90s Have Turned Out Mostly OK
#:games
::: Slashdot

India bans Free Basics, Facebook’s plan to provide free internet to the developing world
#:social media
::: robaeprice ::: kadhimshubber ::: fabiochiusi

Come fare domande in modo intelligente – traduzione italiana
#:manuali, how to
::: Extended Reality

asyncio — Asynchronous I/O, event loop, and concurrency tools
Python
#:algoritmi, codice #:programming, codice, snippet
::: PyMOTW-3

Racket v6.4 is out!
::: racketlang

stepback

Also note that v6.4 fixed a serious security issue in the Racket web server
::: racketlang

Solution to the current Blender hotkey map
#:umorismo
::: kanishk2391

The French data protection authority publicly issues formal notice to FACEBOOK to comply with the French Data Protection Act within three months
#:ditte
::: CNiL

First known hacker-caused power outage signals troubling escalation
#:malware
::: Ars Technica

I premi Turing: Alan Newell e Herbert Simon
#:storia
::: Mr. Palomar

Caz8yRGW4AAB9L4

How the Cloud Has Changed (Since Last You Looked)
#:ditte #:innovazioni, futuro
::: Slashdot

Telegram, la nuova frontiera della Customer Experience di successo
#:social media
::: Tech Economy

E’ emergenza: in rapido aumento i casi di infezione da ransomware Teslacrypt 3.0
#:sicurezza, spionaggio
::: Tech Economy

Research Code vs. Commercial Code
#:programming, codice, snippet #:algoritmi, codice
::: Davide Aversa

Language and Locale Matching in Go
#:linguaggi di programmazione
::: The Go Programming Language

CavNN7cWIAAMoIs

Unix fail
#:umorismo
::: johnregehr

Stallman requested other speakers change their talk titles to say “Free-libre sofware” instead of ”Open-Source”
#:free open source software
::: hubert3

How Complex Systems Fail
::: johnregehr

Programmatic and Direct Manipulation, Together at Last
#:linguaggi di programmazione
::: Lambda the Ultimate

Raspberry Pi’s Raspbian OS Finally Ships With Open-Source OpenGL Support
#:free open source software #:sistemi operativi
::: Slashdot

12717276_10153477553061376_2917691808057320895_n

Maru Is an Android OS on the Phone and Debian Linux When Connected to PC
#:sistemi operativi #:dispositivi mobili
::: Softpedia

In boost to self-driving cars, U.S. tells Google computers can qualify as drivers
#:innovazioni, futuro
::: Reuters

I’m using @overleaf, the free online collaborative LaTeX editor
#:free open source software #:Web, Internet
::: thek3nger

Cyber security, l’ultimatum di Carrai a Minniti
#:sicurezza, spionaggio
::: Lettera 43

The Document Foundation announces #LibreOffice 5.1
#:free open source software
::: tdforg

Ribbon Chapel - NAP Architects

Ribbon Chapel – NAP Architects

Who’s messing with your Internet rights? And who’d tell you if they did?
#:sicurezza, spionaggio
::: PRI

Mac OS X è davvero uno UNIX di serie B?
#:sicurezza, spionaggio #:ditte
::: Codice Insicuro

Beckman, Shockley and the 60th Anniversary of the Birth of Silicon Valley
che storia :grin:
#:storia
::: Computer History Museum

Guide wiki di Gennaio
per gli utenti di Ubuntu
#:sistemi operativi
::: ubuntu-it

Social network: chi decide cosa vediamo?
un archivio online dove rischi di non uscirne più :grin:
#:Web, Internet #:social media
::: Biennale Democrazia

12734191_661446730625152_1388368773275235573_n

Ubik
A small Scheme interpreter and compiler, written in OCaml, for illustrative purposes.
un racketeers di quelli che –OK, come lo sono tutti loro :grin:
#:programmazione funzionale
::: dvanhorn

SCO vs. IBM Battle Over Linux May Finally Be Over
#:sistemi operativi #:frodi #:storia
::: Slashdot

Moore’s law really is dead this time
#:hardware #:innovazioni, futuro
::: Ars Technica

It looks like LIGO is using matplotlib & its new viridis colormap!
#:programming, codice, snippet
::: jakevdp ::: betatim

Crowdfunded Projects Use @Raspberry_Pi
dovrebbe interessare a Winnie (et al., certo)
#:hardware #:algoritmi, codice #:games
::: cnxsoft

946118_878545985576589_4501860585501115739_n

La clausola contrattuale per gestire un’apocalisse zombie proprio mi mancava
#:umorismo
::: midimarcus

Here it comes our 4th birthday with @FablabTorino and the newborn @CasaJasmina
#:innovazioni, futuro #:hardware
::: OfficineArduino

Quel tweet poi rimosso da Andreessen la dice lunga su colonialismo e Silicon Valley
#:ditte #:economia
::: fabiochiusi

Facebook expansion and colonialism share a common pattern
#:ditte #:economia #:Web, Internet
::: fabiochiusi

Beyond the PC toward virtual and augmented reality
#:innovazioni, futuro
::: Daniel Lemire

12728927_10208486699475369_3564056792239743712_n

Guile is a programming language
#:programmazione funzionale
::: GNU

Ci vediamo a “Open Design Conference” a Pordenone?
#:free open source software
::: Dario Cavedon (iced)

Am I the only one wanting an equivalent of the O’Reilly Cookbooks
#:Web, Internet #:algoritmi, codice
::: volothamp

WSJ: Google is working on a standalone VR headset, too
#:ditte #:hardware
::: Engadget

A Worldwide Survey of Encryption Products
#:algoritmi, codice #:sicurezza, spionaggio
::: Serch eLibrary

logo-virgo

Kim Jong-Un Found To Be Mac User
#:umorismo
::: Slashdot

Fossils
#:umorismo
::: SciencePorn

At the coworking space today, someone asked me if I work for NASA
la prendo come una cosa perso :wink:
#:umorismo
::: astrofrog

Convert images to MovingAI maps
#:algoritmi, codice
::: Davide Aversa

I’ve created a graph which illustrates CL implementations
#:lisp e derivati
::: dk_jackdaniel

davvero?

The Easiest Programming Language to Learn Code
#:linguaggi di programmazione
::: Programmer Friendly

Why Apple Fans Have Now Begun To Hate Apple
#:ditte
::: fossbytes

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

Learn Regex The Hard Way
#:programming, codice, snippet
::: Learn Code The Hard Way

Cybersicurezza, l’Italia non è mica Amazon
#:sicurezza, spionaggio
::: il mattino di padova

Jupiter_2_in_Space

Women write better code, study suggests
::: BBC

Signal Processing With GW150914 Open Data
#:programming, codice, snippet
::: LIGO Open Science Center

Researcher illegally shares millions of science papers free online to spread knowledge
#:Web, Internet
::: sciencealert

How the heck does async/await work in Python 3.5?
#:programming, codice, snippet #:algoritmi, codice
::: Brett Cannon

Cute little detail
San Valentino
#:umorismo
::: Electric_Coffee

pericolo_bambini_gender

Rust – il linguaggio – 15

pr6

Strettamente legato al post precedente eccomi qui: /usr/local/share/doc/rust/html/book/patterns.html.

Patterns

Patterns are quite common in Rust. We use them in variable bindings, match statements, and other places, too. Let’s go on a whirlwind tour of all of the things patterns can do!

A quick refresher: you can match against literals directly, and _ acts as an ‘any’ case:

fn main() {
    let x = 1;
    
    match x {
        1 => println!("one"),
        2 => println!("two"),
        3 => println!("three"),
        _ => println!("anything"),
    }
    
}

rs15-0

There’s one pitfall with patterns: like anything that introduces a new binding, they introduce shadowing. For example:

fn main() {
    let x = 'x';
    let c = 'c';
    
    match c {
        x => println!("x: {} c: {}", x, c),
    }
    
    println!("x: {}", x)
    
}

rs15-1

In other words, x => matches the pattern and introduces a new binding named x that’s in scope for the match arm. Because we already have a binding named x, this new x shadows it.
Ummm… io mi penso che il problema sia seduto davanti al ‘puter :roll:

Patterns multipli

You can match multiple patterns with |:

fn main() {
    let x = 1;
    
    match x {
        1 | 2 => println!("one or two"),
        3 => println!("three"),
        _ => println!("anything"),
    }
}

rs15-2

Destructuring

If you have a compound data type, like a struct, you can destructure it inside of a pattern:

fn main() {
    struct Point {
        x: i32,
        y: i32,
    }
    
    let origin = Point { x: 0, y: 0 };
    
    match origin {
        Point { x, y } => println!("({},{})", x, y),
    }
}

rs15-3

We can use : to give a value a different name.

fn main() {
    struct Point {
        x: i32,
        y: i32,
    }
    
    let origin = Point { x: 0, y: 0 };
    
    match origin {
        Point { x: x1, y: y1 } => println!("({},{})", x1, y1),
    }
}

rs15-4

If we only care about some of the values, we don’t have to give them all names:

fn main() {
    struct Point {
        x: i32,
        y: i32,
    }
    
    let origin = Point { x: 0, y: 0 };
    
    match origin {
        Point { x, .. } => println!("x is {}", x),
    }
}

rs15-5

sì, OK, y non viene usato, Rust è pistino ma è per il nostro bene :wink:

You can do this kind of match on any member, not just the first:

fn main() {
    struct Point {
        x: i32,
        y: i32,
    }
    
    let origin = Point { x: 0, y: 0 };
    
    match origin {
        Point { y, .. } => println!("y is {}", y),
    }
}

rs15-6

come sopra :wink:

This ‘destructuring’ behavior works on any compound data type, like tuples or enums.

Ignorare i bindings

You can use _ in a pattern to disregard the type and value. For example, here’s a match against a Result<T, E>:

fn main() {
    let some_value: Result = Err("There was an error");
    match some_value {
        Ok(value) => println!("got a value: {}", value),
        Err(_) => println!("an error occurred"),
    }
}

rs15-7

In the first arm, we bind the value inside the Ok variant to value. But in the Err arm, we use _ to disregard the specific error, and just print a general error message.

_ is valid in any pattern that creates a binding. This can be useful to ignore parts of a larger structure:

fn main() {
    fn coordinate() -> (i32, i32, i32) {
        // generate and return some sort of triple tuple
    (1, 2, 3)
    }
    
    let (x, _, z) = coordinate();
    println!("{},{}", x, z); 
}

rs15-8

sì, modificato :roll:

Here, we bind the first and last element of the tuple to x and z, but ignore the middle element.
Similarly, you can use .. in a pattern to disregard multiple values.

fn main() {
    enum OptionalTuple {
        Value(i32, i32, i32),
        Missing,
    }
    
    let x = OptionalTuple::Value(5, -2, 3);
    
    match x {
        OptionalTuple::Value(..) => println!("Got a tuple!"),
        OptionalTuple::Missing => println!("No such luck."),
    }
}

rs15-9

ref e mut ref

If you want to get a reference, use the ref keyword:

fn main() {
    let x = 5;
    
    match x {
        ref r => println!("Got a reference to {}", r),
    }
}

rs15-10

Here, the r inside the match has the type &i32. In other words, the ref keyword creates a reference, for use in the pattern. If you need a mutable reference, ref mut will work in the same way:

fn main() {
    let mut x = 5;
    
    match x {
        ref mut mr => println!("Got a mutable reference to {}", mr),
    }
}

rs15-11

Ranges

Qui potevo scrivere “intervalli”, lo so :roll: ma si usa?
You can match a range of values with ...:

fn main() {
    let x = 1;
    
    match x {
        1 ... 5 => println!("one through five"),
        _ => println!("anything"),
    }
}

rs15-12

Ranges are mostly used with integers and chars:

fn main() {
    let x = '&';
    
    match x {
        'a' ... 'j' => println!("early letter"),
        'k' ... 'z' => println!("late letter"),
        _ => println!("something else"),
    }
}

rs15-13

Bindings

You can bind values to names with @:

fn main() {
    let x = 1;
    
    match x {
        e @ 1 ... 5 => println!("got a range element {}", e),
        _ => println!("anything"),
    }
}

rs15-14

This is useful when you want to do a complicated match of part of a data structure:

fn main() {
    #[derive(Debug)]
    struct Person {
        name: Option,
    }
    
    let name = "Steve".to_string();
    let mut x: Option = Some(Person { name: Some(name) });
    match x {
        Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a),
        _ => {}
    }
}

rs15-15

OK, un warning ma OK :roll: we’ve bound the inner name to a.

If you use @ with |, you need to make sure the name is bound in each part of the pattern:

fn main() {
    let x = 5;
    
    match x {
        e @ 1 ... 5 | e @ 8 ... 10 => println!("got a range element {}", e),
        _ => println!("anything"),
    }
}

rs15-16

Guards

You can introduce ‘match guards’ with if:

fn main() {
    enum OptionalInt {
        Value(i32),
        Missing,
    }
    
    let x = OptionalInt::Value(5);
    
    match x {
        OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"),
        OptionalInt::Value(..) => println!("Got an int!"),
        OptionalInt::Missing => println!("No such luck."),
    }
}

rs15-17

If you’re using if with multiple patterns, the if applies to both sides:

fn main() {
    let x = 4;
    let y = false;
    
    match x {
        4 | 5 if y => println!("yes"),
        _ => println!("no"),
    }
}

rs15-18

This prints no, because the if applies to the whole of 4 | 5, and not to just the 5. In other words, the precedence of if behaves like this:

(4 | 5) if y => ...

not this:

4 | (5 if y) => ...

Mix and Match

Whew! That’s a lot of different ways to match things, and they can all be mixed and matched, depending on what you’re doing:

match x {
    Foo { x: Some(ref name), y: None } => ...
}

Patterns are very powerful. Make good use of them.
Vario e interessante come il rosario :roll: OK, più vario del rosario :grin:

:mrgreen:

Rust – il linguaggio – 14

tttwContinuando da qui oggi ecco /usr/local/share/doc/rust/html/book/match.html.

Match

Often, a simple if/else isn’t enough, because you have more than two possible options. Also, conditions can get quite complex. Rust has a keyword, match, that allows you to replace complicated if/else groupings with something more powerful. Check it out:

fn main() {
    let x = 5;
    
    match x {
        1 => println!("one"),
        2 => println!("two"),
        3 => println!("three"),
        4 => println!("four"),
        5 => println!("five"),
        _ => println!("something else"),
    }
    
}

rs14-0OK, quello che altri chiama select o case :wink:
match takes an expression and then branches based on its value. Each ‘arm’ of the branch is of the form val => expression. When the value matches, that arm’s expression will be evaluated. It’s called match because of the term ‘pattern matching’, which match is an implementation of. There’s an entire section on patterns that covers all the patterns that are possible here. Nel prossimo post, promesso :wink:

So what’s the big advantage? Well, there are a few. First of all, match enforces ‘exhaustiveness checking’. Do you see that last arm, the one with the underscore (_)? If we remove that arm, Rust will give us an error:

error: non-exhaustive patterns: `_` not covered

In other words, Rust is trying to tell us we forgot a value. Because x is an integer, Rust knows that it can have a number of different values – for example, 6. Without the _, however, there is no arm that could match, and so Rust refuses to compile the code. _ acts like a ‘catch-all arm’. If none of the other arms match, the arm with _ will, and since we have this catch-all arm, we now have an arm for every possible value of x, and so our program will compile successfully.

match is also an expression, which means we can use it on the right-hand side of a let binding or directly where an expression is used:

fn main() {
    let x = 5;
    
    let number = match x {
        1 => "one",
        2 => "two",
        3 => "three",
        4 => "four",
        5 => "five",
        _ => "something else",
    };
    println!("number = {}", number);
}

rs14-1Sometimes it’s a nice way of converting something from one type to another.

Matching con enums

Another important use of the match keyword is to process the possible variants of an enum:

fn main() {
    enum Message {
        Quit,
        ChangeColor(i32, i32, i32),
        Move { x: i32, y: i32 },
        Write(String),
    }
    
    fn quit() { /* ... */ }
    fn change_color(r: i32, g: i32, b: i32) { /* ... */ }
    fn move_cursor(x: i32, y: i32) { /* ... */ }
    
    fn process_message(msg: Message) {
        match msg {
            Message::Quit => quit(),
            Message::ChangeColor(r, g, b) => change_color(r, g, b),
            Message::Move { x: x, y: y } => move_cursor(x, y),
            Message::Write(s) => println!("{}", s),
        };
    }
}

Compilandolo ottieni una sfilza di warnings (variabili e funzioni non usate) lunga così :roll:

Again, the Rust compiler checks exhaustiveness, so it demands that you have a match arm for every variant of the enum. If you leave one off, it will give you a compile-time error unless you use _.

Unlike the previous uses of match, you can’t use the normal if statement to do this. You can use the if let statement [ancora da vedere, prossimamente], which can be seen as an abbreviated form of match.

:mrgreen:

Rust – il linguaggio – 13

2zN

Eccomi qui /usr/local/share/doc/rust/html/book/enums.html, proseguendo da qui.

Enums

An enum in Rust is a type that represents data that could be one of several possible variants:

enum Message {
    Quit,
    ChangeColor(i32, i32, i32),
    Move { x: i32, y: i32 },
    Write(String),
}

Each variant can optionally have data associated with it. The syntax for defining variants resembles the syntaxes used to define structs: you can have variants with no data (like unit-like structs), variants with named data, and variants with unnamed data (like tuple structs). Unlike separate struct definitions, however, an enum is a single type. A value of the enum can match any of the variants. For this reason, an enum is sometimes called a ‘sum type’: the set of possible values of the enum is the sum of the sets of possible values for each variant.

We use the :: syntax to use the name of each variant: they’re scoped by the name of the enum itself. This allows both of these to work:

let x: Message = Message::Move { x: 3, y: 4 };

enum BoardGameTurn {
    Move { squares: i32 },
    Pass,
}

let y: BoardGameTurn = BoardGameTurn::Move { squares: 1 };

Both variants are named Move, but since they’re scoped to the name of the enum, they can both be used without conflict.

A value of an enum type contains information about which variant it is, in addition to any data associated with that variant. This is sometimes referred to as a ‘tagged union’, since the data includes a ‘tag’ indicating what type it is. The compiler uses this information to enforce that you’re accessing the data in the enum safely. For instance, you can’t simply try to destructure a value as if it were one of the possible variants:

fn process_color_change(msg: Message) {
    let Message::ChangeColor(r, g, b) = msg; // compile-time error
}

Not supporting these operations may seem rather limiting, but it’s a limitation which we can overcome. There are two ways: by implementing equality ourselves, or by pattern matching variants with match expressions, which you’ll learn in the next section. We don’t know enough about Rust to implement equality yet, but we’ll find out in the traits section.

(Solo per Davide: ahemmm… no, questa volta non lo scrivo :wink: ).

Costruttori come funzioni

An enum’s constructors can also be used like functions. For example:

let m = Message::Write("Hello, world".to_string());

is the same as

fn foo(x: String) -> Message {
    Message::Write(x)
}

let x = foo("Hello, world".to_string());

This is not immediately useful to us, but when we get to closures, we’ll talk about passing functions as arguments to other functions. For example, with iterators, we can do this to convert a vector of Strings into a vector of Message::Writes:

let v = vec!["Hello".to_string(), "World".to_string()];
let v1: Vec<Message> = v.into_iter().map(Message::Write).collect();

Ahemmm… :roll: vale l’osservazione di prima, per adesso. È un post che troverà la giustificazione in futuro :grin:

:mrgreen:

Non solo SpaceGames

usborne_computer_books-702x336Il post Computer SpaceGames deve essere considerato solo in inizio :grin:
Sì perché ecco il meraviglioso annuncio: Usborne Releases 1980s Coding Books As Free PDFs.

Raspberry-Pi-Spy-Logo-140x140-OutlineUh! ‘n sito (non ufficiale) dedicato al Raspberry Pi :grin:

Io adesso sarò molto impegnato, prima a scaricare e poi a studiare, sapete com’è allora ero indaffarato su altre cose. Ma voglio aggiornarmi.

Inoltre assolutamente da segnalare: The Official Raspberry Pi Projects Book.

:mrgreen:

Rust – il linguaggio – 12

117

Continuando da qui oggi sono qui: /usr/local/share/doc/rust/html/book/structs.html.

Structs

structs are a way of creating more complex data types. For example, if we were doing calculations involving coordinates in 2D space, we would need both an x and a y value:

let origin_x = 0;
let origin_y = 0;

A struct lets us combine these two into a single, unified datatype:

struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let origin = Point { x: 0, y: 0 }; // origin: Point

    println!("The origin is at ({}, {})", origin.x, origin.y);
}

rs12-0There’s a lot going on here, so let’s break it down. We declare a struct with the struct keyword, and then with a name. By convention, structs begin with a capital letter and are camel cased: PointInSpace, not Point_In_Space.

We can create an instance of our struct via let, as usual, but we use a key: value style syntax to set each field. The order doesn’t need to be the same as in the original declaration.

Finally, because fields have names, we can access the field through dot notation: origin.x.

The values in structs are immutable by default, like other bindings in Rust. Use mut to make them mutable:

struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let mut point = Point { x: 0, y: 0 };

    point.x = 5;

    println!("The point is at ({}, {})", point.x, point.y);
}

rs12-1Rust does not support field mutability at the language level, so you cannot write something like this:

struct Point {  
    mut x: i32,  // nope!
    y: i32,
}

Mutability is a property of the binding, not of the structure itself. If you’re used to field-level mutability, this may seem strange at first, but it significantly simplifies things. It even lets you make things mutable for a short time only:

struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let mut point = Point { x: 0, y: 0 };

    point.x = 5;

    let point = point; // this new binding can’t change now

    point.y = 6; // this causes an error
}

rs12-2

Aggiornamento della sintassi

“Update syntax” dice la guida.
A struct can include .. to indicate that you want to use a copy of some other struct for some of the values. For example:

struct Point3d {
    x: i32,
    y: i32,
    z: i32,
}

This gives point a new y, but keeps the old x and z values. It doesn’t have to be the same struct either, you can use this syntax when making new ones, and it will copy the values you don’t specify:

fn main() {
    struct Point3d {
        x: i32,
        y: i32,
        z: i32,
    }
    let origin = Point3d { x: 0, y: 0, z: 0 };
    let point = Point3d { z: 1, x: 2, .. origin };
    println!("The origin is at ({}, {}, {})", origin.x, origin.y, origin.z);
    println!("The point is at ({}, {}, {})", point.x, point.y, point.z);
   
}

rs12-3

Tuple structs

Rust has another data type that’s like a hybrid between a tuple and a struct, called a ‘tuple struct’. Tuple structs have a name, but their fields don’t:

struct Color(i32, i32, i32);
struct Point(i32, i32, i32);

These two will not be equal, even if they have the same values:

let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);

It is almost always better to use a struct than a tuple struct. We would write Color and Point like this instead:

struct Color {
    red: i32,
    blue: i32,
    green: i32,
}

struct Point {
    x: i32,
    y: i32,
    z: i32,
}

Now, we have actual names, rather than positions. Good names are important, and with a struct, we have actual names.

There is one case when a tuple struct is very useful, though, and that’s a tuple struct with only one element. We call this the ‘newtype’ pattern, because it allows you to create a new type, distinct from that of its contained value and expressing its own semantic meaning:

fn main() {
    struct Inches(i32);
    
    let length = Inches(10);
    
    let Inches(integer_length) = length;
    println!("length is {} inches", integer_length);
    
}

rs12-4As you can see here, you can extract the inner integer type through a destructuring let, just as with regular tuples. In this case, the let Inches(integer_length) assigns 10 to integer_length.
Ci devo pensare su un po’ :roll:

Unit-like structs

You can define a struct with no members at all:

struct Electron;
let x = Electron;

Such a struct is called ‘unit-like’ because it resembles the empty tuple, (), sometimes called ‘unit’. Like a tuple struct, it defines a new type.

This is rarely useful on its own (although sometimes it can serve as a marker type), but in combination with other features, it can become useful. For instance, a library may ask you to create a structure that implements a certain trait to handle events. If you don’t have any data you need to store in the structure, you can just create a unit-like struct.

OK, le structs si confermano ancora una volta –come dire– dagli anni ’80… :roll:

:mrgreen:

Rust – il linguaggio – 11

CaKOggi qui: /usr/local/share/doc/rust/html/book/mutability.html proseguendo da qui.

Mutabilità

Mutability, the ability to change something, works a bit differently in Rust than in other languages. The first aspect of mutability is its non-default status:

let x = 5;
x = 6; // error!

We can introduce mutability with the mut keyword:

let mut x = 5;
x = 6; // no problem!

This is a mutable variable binding. When a binding is mutable, it means you’re allowed to change what the binding points to. So in the above example, it’s not so much that the value at x is changing, but that the binding changed from one i32 to another.

If you want to change what the binding points to, you’ll need a mutable reference:

let mut x = 5;
let y = &mut x;

y is an immutable binding to a mutable reference, which means that you can’t bind y to something else (y = &mut z), but you can mutate the thing that’s bound to y (*y = 5). A subtle distinction.

Of course, if you need both:

let mut x = 5;
let mut y = &mut x;

Now y can be bound to another value, and the value it’s referencing can be changed.

It’s important to note that mut is part of a pattern, so you can do things like this:

let (mut x, y) = (5, 6);
fn foo(mut x: i32) {

Mutabilità interna e esterna

Così ho tradotto “Interior vs. Exterior Mutability”.
However, when we say something is ‘immutable’ in Rust, that doesn’t mean that it’s not able to be changed: we mean something has ‘exterior mutability’. Consider, for example, Arc<T>:

use std::sync::Arc;
let x = Arc::new(5);
let y = x.clone();

When we call clone(), the Arc<T> needs to update the reference count. Yet we’ve not used any muts here, x is an immutable binding, and we didn’t take &mut 5 or anything. So what gives?

To understand this, we have to go back to the core of Rust’s guiding philosophy, memory safety, and the mechanism by which Rust guarantees it, the ownership system, and more specifically, borrowing:

You may have one or the other of these two kinds of borrows, but not both at the same time:

  • one or more references (&T) to a resource,
  • exactly one mutable reference (&mut T).

So, that’s the real definition of ‘immutability’: is this safe to have two pointers to? In Arc<T>’s case, yes: the mutation is entirely contained inside the structure itself. It’s not user facing. For this reason, it hands out &T with clone(). If it handed out &mut Ts, though, that would be a problem.

Other types, like the ones in the std::cell module, have the opposite: interior mutability. For example:

use std::cell::RefCell;
let x = RefCell::new(42);
let y = x.borrow_mut();

RefCell hands out &mut references to what’s inside of it with the borrow_mut() method. Isn’t that dangerous? What if we do:

use std::cell::RefCell;
let x = RefCell::new(42);
let y = x.borrow_mut();
let z = x.borrow_mut();

This will in fact panic, at runtime. This is what RefCell does: it enforces Rust’s borrowing rules at runtime, and panic!s if they’re violated. This allows us to get around another aspect of Rust’s mutability rules. Let’s talk about it first.

Mutabilità field-level

Mutability is a property of either a borrow (&mut) or a binding (let mut). This means that, for example, you cannot have a struct with some fields mutable and some immutable:

struct Point {     
    x: i32,
    mut y: i32, // nope
}

The mutability of a struct is in its binding:

struct Point {
    x: i32,
    y: i32,
}

However, by using Cell<T>, you can emulate field-level mutability:

fn main() {
    use std::cell::Cell;
    
    struct Point {
        x: i32,
        y: Cell,
    }
    
    let point = Point { x: 5, y: Cell::new(6) };
    
    point.y.set(7);
    
    println!("y: {:?}", point.y);
    
}

rs11-0We’ve successfully updated y.

Uhmmm… ed è ancora lunga… :roll:
:mrgreen:

Computer SpaceGames

csg
Forse non vale; forse sto facendo una cosa non corretta ma devo farla.
Anche perché io ho cominciato troppo presto ma conosco chi ha vissuto in pieno questa era: quella del Basic, quella dei primi PC, l’inizio dell’era moderna, che ha messo KO i dinosauri, manframes e mini (i mini –ehi! il mio Pr1me— non erano per niente mini, erano armadi quattro stagioni).
Allora quando ho visto il tweet di John Regehr: I had this book ho visto che dovevo dirlo a tutti quelli che non seguono John su Twitter.

Über-fantastico vero?
Del Pr1me ne parlavo, tanto tempo fa, qui.

Rust – il linguaggio – 10

m4

Continuando da qui oggi ecco /usr/local/share/doc/rust/html/book/lifetimes.html.

Lifetimes

Sì contina con i due post precedenti sull’ownership. These three chapters are related, and in order. You’ll need all three to fully understand the ownership system.

Salto il paragrafo “Meta”, sempre uguale.

Lending out a reference to a resource that someone else owns can be complicated. For example, imagine this set of operations:

  • I acquire a handle to some kind of resource.
  • I lend you a reference to the resource.
  • I decide I’m done with the resource, and deallocate it, while you still have your reference.
  • You decide to use the resource.

Uh oh! Your reference is pointing to an invalid resource. This is called a dangling pointer or ‘use after free’, when the resource is memory.

To fix this, we have to make sure that step four never happens after step three. The ownership system in Rust does this through a concept called lifetimes, which describe the scope that a reference is valid for.

When we have a function that takes a reference by argument, we can be implicit or explicit about the lifetime of the reference:

// implicit
fn foo(x: &i32) {
}

// explicit
fn bar<'a>(x: &'a i32) {
}

The 'a reads ‘the lifetime a’. Technically, every reference has some lifetime associated with it, but the compiler lets you elide (i.e. omit, see “Lifetime Elision” below) them in common cases. Before we get to that, though, let’s break the explicit example down:

fn bar<'a>(...)

We previously talked a little about function syntax [/usr/local/share/doc/rust/html/book/functions.html], but we didn’t discuss the <>s after a function’s name. A function can have ‘generic parameters’ between the <>s, of which lifetimes are one kind. We’ll discuss other kinds of generics later in the book [/usr/local/share/doc/rust/html/book/generics.html], but for now, let’s just focus on the lifetimes aspect.

We use <> to declare our lifetimes. This says that bar has one lifetime, 'a. If we had two reference parameters, it would look like this:

fn bar<'a, 'b>(...)

Then in our parameter list, we use the lifetimes we’ve named:

...(x: &'a i32)

If we wanted an &mut reference, we’d do this:

...(x: &'a mut i32)

If you compare &mut i32 to &'a mut i32, they’re the same, it’s just that the lifetime 'a has snuck in between the & and the mut i32. We read &mut i32 as ‘a mutable reference to an i32’ and &'a mut i32 as ‘a mutable reference to an i32 with the lifetime 'a’.

Nelle struct

You’ll also need explicit lifetimes when working with structs:

struct Foo {
    x: &'a i32,
}

fn main() {
    let y = &5; // this is the same as `let _y = 5; let y = &_y;`
    let f = Foo { x: y };

    println!("{}", f.x);
}

rs10-0As you can see, structs can also have lifetimes. In a similar way to functions,

struct Foo<'a> {

declares a lifetime, and

x: &'a i32

uses it. So why do we need a lifetime here? We need to ensure that any reference to a Foo cannot outlive the reference to an i32 it contains.

Blocchi impl

Let’s implement a method on Foo:

struct Foo {
    x: &'a i32,
}

impl Foo {
    fn x(&self) -> &'a i32 { self.x }
}

fn main() {
    let y = &5; // this is the same as `let _y = 5; let y = &_y;`
    let f = Foo { x: y };

    println!("x is: {}", f.x());
}

rs10-1As you can see, we need to declare a lifetime for Foo in the impl line. We repeat 'a twice, just like on functions: impl<'a> defines a lifetime 'a, and Foo<'a> uses it.
Ahemmm:roll:

Lifetimes multiple

If you have multiple references, you can use the same lifetime multiple times:

fn x_or_y<'a>(x: &'a str, y: &'a str) -> &'a str {

This says that x and y both are alive for the same scope, and that the return value is also alive for that scope. If you wanted x and y to have different lifetimes, you can use multiple lifetime parameters:

fn x_or_y<'a, 'b>(x: &'a str, y: &'b str) -> &'a str {

In this example, x and y have different valid scopes, but the return value has the same lifetime as x.

Pensare per scopes

A way to think about lifetimes is to visualize the scope that a reference is valid for. For example:

fn main() {
    let y = &5;     // -+ y goes into scope
                    //  |
    // stuff        //  |
                    //  |
}                   // -+ y goes out of scope

Adding in our Foo:

struct Foo {
    x: &'a i32,
}

fn main() {
    let y = &5;           // -+ y goes into scope
    let f = Foo { x: y }; // -+ f goes into scope
    // stuff              //  |
                          //  |
}                         // -+ f and y go out of scope

Our f lives within the scope of y, so everything works. What if it didn’t? This code won’t work:

struct Foo {
    x: &'a i32,
}

fn main() {
    let x;                    // -+ x goes into scope
                              //  |
    {                         //  |
        let y = &5;           // ---+ y goes into scope
        let f = Foo { x: y }; // ---+ f goes into scope
        x = &f.x;             //  | | error here
    }                         // ---+ f and y go out of scope
                              //  |
    println!("{}", x);        //  |
}

rs10-2atz! :shock: Whew! As you can see here, the scopes of f and y are smaller than the scope of x. But when we do x = &f.x, we make x a reference to something that’s about to go out of scope.

Named lifetimes are a way of giving these scopes a name. Giving something a name is the first step towards being able to talk about it.

'static

The lifetime named ‘static’ is a special lifetime. It signals that something has the lifetime of the entire program. Most Rust programmers first come across 'static when dealing with strings:

let x: &'static str = "Hello, world.";

String literals have the type &'static str because the reference is always alive: they are baked into the data segment of the final binary. Another example are globals:

static FOO: i32 = 5;
let x: &'static i32 = &FOO;

This adds an i32 to the data segment of the binary, and x is a reference to it.

Lifetime elision

Rust supports powerful local type inference in function bodies, but it’s forbidden in item signatures to allow reasoning about the types based on the item signature alone. However, for ergonomic reasons a very restricted secondary inference algorithm called “lifetime elision” applies in function signatures. It infers only based on the signature components themselves and not based on the body of the function, only infers lifetime parameters, and does this with only three easily memorizable and unambiguous rules. This makes lifetime elision a shorthand for writing an item signature, while not hiding away the actual types involved as full local inference would if applied to it. (Cioè :shock: mica sicuro di aver capito :roll:, spero che la spiegazione renda questa frase barocca e principalmente decorativa).

When talking about lifetime elision, we use the term input lifetime and output lifetime. An input lifetime is a lifetime associated with a parameter of a function, and an output lifetime is a lifetime associated with the return value of a function. For example, this function has an input lifetime:

fn foo<'a>(bar: &'a str)

This one has an output lifetime:

fn foo<'a>() -> &'a str

This one has a lifetime in both positions:

fn foo<'a>(bar: &'a str) -> &'a str

Here are the three rules:

  • Each elided lifetime in a function’s arguments becomes a distinct lifetime parameter.
  • If there is exactly one input lifetime, elided or not, that lifetime is assigned to all elided lifetimes in the return values of that function.
  • If there are multiple input lifetimes, but one of them is &self or &mut self, the lifetime of self is assigned to all elided output lifetimes.

Otherwise, it is an error to elide an output lifetime.

Esempi

Here are some examples of functions with elided lifetimes. We’ve paired each example of an elided lifetime with its expanded form.

fn print(s: &str); // elided
fn print(s: &'a str); // expanded

fn debug(lvl: u32, s: &str); // elided
fn debug(lvl: u32, s: &'a str); // expanded

// In the preceding example, `lvl` doesn’t need a lifetime because it’s not a
// reference (`&`). Only things relating to references (such as a `struct`
// which contains a reference) need lifetimes.

fn substr(s: &str, until: u32) -> &str; // elided
fn substr(s: &'a str, until: u32) -> &'a str; // expanded

fn get_str() -> &str; // ILLEGAL, no inputs

fn frob(s: &str, t: &str) -> &str; // ILLEGAL, two inputs
fn frob(s: &'a str, t: &'b str) -> &str; // Expanded: Output lifetime is ambiguous

fn get_mut(&mut self) -> &mut T; // elided
fn get_mut(&'a mut self) -> &'a mut T; // expanded

fn args(&mut self, args: &[T]) -> &mut Command; // elided
fn args(&'a mut self, args: &'b [T]) -> &'a mut Command; // expanded

fn new(buf: &mut [u8]) -> BufWriter; // elided
fn new(buf: &'a mut [u8]) -> BufWriter; // expanded

:evil: quasi panico, forse.

:mrgreen:

Visto nel Web – 221

Allora oggi ci sono le categorie, ancora provvisorie, devo migliorarele, servono suggerimenti. CMQ ecco cosa ho visto nel Web.

domenico-scilipoti
Internet speed in Europe
#:Web, Internet
::: ianbremmer

Data about os used at the FOSDEM
#:free open source software
::: Google+

General birthday problem
#:algoritmi, codice
::: John D. Cook

European SpaceDataHighway’s first satellite lifts off
#:hardware #:sicurezza, spionaggio
::: Engadget

Apple: Losing Out On Talent and In Need of a Killer New Device
#:ditte
::: Slashdot

nq160122

Un attacco informatico e 50 milioni di euro in fumo … quale lezione?
#:sicurezza, spionaggio
::: Tech Economy

What is open hardware?
#:hardware #:free open source software
::: Opensource

Here’s some of the Apollo 11 source code
#:storia
::: randal_olson

Rust for Web
#:linguaggi di programmazione
::: Medium

Microsoft Edge’s Private Browsing Mode Isn’t Actually Private
#:sicurezza, spionaggio
::: Slashdot

CZUQtAcW0AAUjaM

Feature Comparison: LibreOffice – Microsoft Office
#:free open source software
::: The Document Foundation

Big Satellite Systems, Simulated On Your Desktop
#:Web, Internet #:innovazioni, futuro
::: Slashdot

La Marca monomarca
#:free open source software
::: Tech Economy

#madswag
#:economia #:spam
::: kOoLiNuS

RTFM
#:sistemi operativi
::: cosmo e dintorni

2012-05-31-einstein

Back to the stone age!
#:dispositivi mobili #:umorismo
::: SciencePorn

#lisp Picrin – a lightweight R7RS scheme implementation in pure C89
#:lisp e derivati
::: reddit_lisp

#lisp SBCL 1.3.2 released! | redd.it/43kuq7
io sono fermo a 1.2.14, come passa il tempo; sono vecchio :roll:
#:lisp e derivati
::: reddit_lisp

emacs is like a hobby
#:umorismo
::: ErgoEmacs

Mary livecodes a drum machine
#:algoritmi, codice
::: Mary Rose Cook

road

Default random-number generators are slow
#:algoritmi, codice
::: Daniel Lemire

How To Build a TimesMachine
#:algoritmi, codice #:storia #:dati, raccolta
::: Slashdot

Alphabet Becomes The Most Valuable Public Company In The World
#:ditte
::: TechCrunch

Harvard: No, Crypto Isn’t Making the FBI Go Dark
#:sicurezza, spionaggio
::: Slashdot

The Guix System Distribution
#:sistemi operativi #:free open source software
::: GNU

dark-side

On WebKit Security Updates
#:sicurezza, spionaggio
::: GNOME Blogs

“Così abbiamo convinto il Ministero della Difesa a convertirsi all’open-source”
#:free open source software
::: Motherboard

Expand Your #Programming Vocabulary (for Beginners)
#:linguaggi di programmazione
::: Donearm

Backslashes
#:umorismo
::: xkcd

12647446_1294591863904147_7754700145032717863_n

Safe Harbor addio, arriva il nuovo accordo Privacy Shield tra Europa e USA
#:sicurezza, spionaggio #:dati, raccolta
::: Downloadblog

8 non-code ways to contribute to open source
#:free open source software
::: Opensource

Microsoft steps up AI push with Swiftkey deal
#:ditte
::: Financial Times

Gavin McGimpsey wrote a nice macro outline as an introduction to Racket macros
#:lisp e derivati
::: racketlang

Tianhe-2 is the world’s fastest supercomputer powered by Linux
#:sistemi operativi
::: letozaf

12670617_10208843459187057_3563909602246832200_n

The TPP is a continuation of our disastrous trade policies that have devastated manufacturing cities and towns all over this country
#:economia
::: BernieSanders

Latest #Windows10 May Have a #Linux Subsystem Hidden Inside!
#:sistemi operativi
::: EPietrafesa

Be sure to read our #PrivacyShield fact sheet to better understand the agreement
#:sicurezza, spionaggio
::: CommerceGov

Linux 0.11 source code
#:storia #:sistemi operativi #:free open source software
::: gigitux

UN panel ‘rules in Julian Assange’s favour’
#:sicurezza, spionaggio
::: BBC ::: la Repubblica

CaKOa5rWYAAMWEC

Google’s new head of search is an AI research leader
#:ditte #:algoritmi, codice
::: Engadget

Today, 77% of adults ages 30-49 use social media, compared with 8% in 2005
#:social media
::: pewinternet

This looks big, if early reports are correct: UN finds UK unlawfully detained @WikiLeaks founder #Assange
#:sicurezza, spionaggio
::: Snowden

Torrents Time Lets Anyone Launch Their Own Web Version of Popcorn Time
#:Web, Internet
::: Slashdot

Fear of Macros
#:lisp e derivati
devo ancora leggerlo, poi vi racconto :wink:
::: Greg Hendershott

CaP4aLIWAAIeuxg

Latest Windows 10 May Have a Linux Subsystem Hidden Inside
#:sistemi operativi
::: The Hacker News

With Rand Paul out of the race, is there anyone left to fight the NSA?
#:sicurezza, spionaggio
::: The Verge

L’ultrabroadband in Italia
#:Web, Internet
::: manteblog

GNU Guile 2.1.2 released!
::: davexunit

Mozilla to end development on Firefox OS for smartphones after v2.6
::: daw985

vRF9b47

ABC della sicurezza: Furto di Identità
#:sicurezza, spionaggio
::: Tech Economy

“Sfiduciati” sulla strada del CAD: coinvolgiamo tutti gli stakeholder
::: Forum PA

Apple, pizza e mandolino
#:ditte
::: Un altro orizzonte

New Concurrent Hash Maps for C++
#:algoritmi, codice
::: Preshing on Programming

A Brief History of Open Source Code – Infographic by Kinvey
#:free open source software #:storia
::: BSD MAG

CaZTSXjWEAALCet

Privacy, il nuovo accordo tra Europa e Usa ci tutela davvero?
#:sicurezza, spionaggio
::: L’Espresso

AI Is Transforming Google Search. The Rest of the Web Is Next
#:ditte #:innovazioni, futuro #:Web, Internet
::: Wired

Riconoscere un font
::: patfumetto

Heisenberg developers
#:programming, codice, snippet
::: Grab the Blaster

Marco Rubio Wants To Permanently Extend NSA Mass Surveillance
#:sicurezza, spionaggio
::: Slashdot

12654482_10208805769971395_5498060997450067380_n

Firefox 44 Deletes Fine-Grained Cookie Management
#:Web, Internet #:sicurezza, spionaggio
::: Slashdot

Renzi, Carrai e Padoan. Cosa succede davvero sulla cyber security
#:sicurezza, spionaggio
::: Formiche

Wearable Devices Market Worth $28.7 Billion In 2016: Smartwatch To Drive the Growth
#:dispositivi mobili
::: Dazeinfo

The Essence of Scala
#:programmazione funzionale
::: Scala

X projects: Alphabet’s ‘moonshot’ ventures that could change the world
#:ditte #:innovazioni, futuro
::: the Guardian

12669607_946359752079504_4494371113854956777_n

Error 53: Apple remotely bricks phones to punish customers for getting independent repairs
#:ditte
::: Boing Boing

Writing an Infrared Logic Analyser in Racket
#:lisp e derivati
::: (expr:labs)

Racket ships with a fantastic tileset for 2D games
#:lisp e derivati
::: thelittlelisper

Callback Hell: A guide to asynchronous #JavaScript programming
#:linguaggi di programmazione
::: Donearm

Brotli has potential to replace GZIP for compression of dynamic assets
#:algoritmi, codice
::: openwebdaily

12647115_537654666395690_8314991193723485884_n

The Performance of Ubuntu Linux Over the Past 10 Years
#:sistemi operativi
::: Slashdot

Don’t Sleep On New Data Privacy Regulations
#:sicurezza, spionaggio
::: TechCrunch

Six degrees of separation?
#:sicurezza, spionaggio #:Web, Internet
::: Snowden

The Linux user experience
#:umorismo
::: thegrugq

Modern Java – A Guide to Java 8
#:manuali, how to #:linguaggi di programmazione
::: winterbe
CaiaevoW0AAvpr3

Iscriviti

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

Segui assieme ad altri 89 follower