Haskell – 162 – Moduli – 2

Continuo da qui, copio qui.

Inports gerarchici
Though technically not part of the Haskell 98 standard, most Haskell compilers support hierarchical imports. This was designed to get rid of clutter in the directories in which modules are stored. Hierarchical imports allow you to specify (to a certain degree) where in the directory structure a module exists. For instance, if you have a “haskell” directory on your computer and this directory is in your compiler’s path (see your compiler notes for how to set this; in GHC it’s “-i“, in Hugs it’s “-P“), then you can specify module locations in subdirectories to that directory.

Suppose instead of saving the “Cards” module in your general haskell directory, you created a directory specifically for it called “Cards“. The full path of the Cards.hs file is then haskell/Cards/Cards.hs (or, for Windows haskell\Cards\Cards.hs). If you then change the name of the Cards module to “Cards.Cards“, as in:

module Cards.Cards(...)
    where

...

You could then import it in any module, regardless of this module’s directory, as:

import Cards.Cards

If you start importing these module qualified, I highly recommend using the as keyword to shorten the names, so you can write:

import qualified Cards.Cards as Cards

... Cards.newDeck ...

instead of:

import qualified Cards.Cards

... Cards.Cards.newDeck ...

which tends to get ugly. Ovvio 😉

👽

Annunci

Haskell – 161 – Moduli – 1

Continuo da qui, copio qui.

In Haskell, program subcomponents are divided into modules. Each module sits in its own file and the name of the module should match the name of the file (without the “.hs” extension, of course), if you wish to ever use that module in a larger program.

For instance, suppose I am writing a game of poker. I may wish to have a separate module called “Cards” to handle the generation of cards, the shuffling and the dealing functions, and then use this “Cards” module in my “Poker” modules. That way, if I ever go back and want to write a blackjack program, I don’t have to rewrite all the code for the cards; I can simply import the old “Cards” module.

Exports
Suppose as suggested we are writing a cards module. I have left out the implementation details, but suppose the skeleton of our module looks something like this:

module Cards
    where

data Card = ...
data Deck = ...

newDeck :: ... -> Deck
newDeck = ...

shuffle :: ... -> Deck -> Deck
shuffle = ...

-- 'deal deck n' deals 'n' cards from 'deck'
deal :: Deck -> Int -> [Card]
deal deck n = dealHelper deck n []

dealHelper = ...

In this code, the function deal calls a helper function dealHelper. The implementation of this helper function is very dependent on the exact data structures you used for Card and Deck so we don’t want other people to be able to call this function. In order to do this, we create an export list, which we insert just after the module name declaration:

module Cards ( Card(),
               Deck(),
               newDeck,
               shuffle,
               deal
             )
    where

...

Here, we have specified exactly what functions the module exports, so people who use this module won’t be able to access our dealHelper function. The () after Card and Deck specify that we are exporting the type but none of the constructors. For instance if our definition of Card were:

data Card = Card Suit Face
data Suit = Hearts
          | Spades
          | Diamonds
          | Clubs
data Face = Jack
          | Queen
          | King
          | Ace
          | Number Int

Then users of our module would be able to use things of type Card, but wouldn’t be able to construct their own Cards and wouldn’t be able to extract any of the suit/face information stored in them.

If we wanted users of our module to be able to access all of this information, we would have to specify it in the export list:

module Cards ( Card(Card),
               Suit(Hearts,Spades,Diamonds,Clubs),
               Face(Jack,Queen,King,Ace,Number),
               ...
             )
    where

...

This can get frustrating if you’re exporting datatypes with many constructors, so if you want to export them all, you can simply write (..), as in:

module Cards ( Card(..),
               Suit(..),
               Face(..),
               ...
             )
    where

...

And this will automatically export all the constructors.

Imports
There are a few idiosyncrasies in the module import system, but as long as you stay away from the corner cases, you should be fine. Suppose, as before, you wrote a module called “Cards” which you saved in the file “Cards.hs“. You are now writing your poker module and you want to import all the definitions from the “Cards” module. To do this, all you need to do is write:

module Poker
    where

import Cards

This will enable you to use any of the functions, types and constructors exported by the module “Cards“. You may refer to them simply by their name in the “Cards” module (as, for instance, newDeck), or you may refer to them explicitly as imported from “Cards” (as, for instance, Cards.newDeck). It may be the case that two modules export functions or types of the same name. In these cases, you can import one of the modules qualified which means that you would no longer be able to simply use the newDeck format but must use the longer Cards.newDeck format, to remove ambiguity. If you wanted to import “Cards” in this qualified form, you would write:

import qualified Cards

Another way to avoid problems with overlapping function definitions is to import only certain functions from modules. Suppose we knew the only function from “Cards” that we wanted was newDeck, we could import only this function by writing:

import Cards (newDeck)

On the other hand, suppose we knew that that the deal function overlapped with another module, but that we didn’t need the “Cards” version of that function. We could hide the definition of deal and import everything else by writing:

import Cards hiding (deal)

Finally, suppose we want to import “Cards” as a qualified module, but don’t want to have to type Cards. out all the time and would rather just type, for instance, C. — we could do this using the as keyword:

import qualified Cards as C

These options can be mixed and matched — you can give explicit import lists on qualified/as imports, for instance.

👽

Visto nel Web – 335

Tempi difficili. Non bastava #Facebookgate, adesso si attenta anche Butac censurata. Per intanto ecco cosa ho wisto nel Web.

Linux Device Driver Synthesis and Verification
#:sistemi operativi
::: b3h3m0th

“Are dogs appreciated fairly on @dog_rates?” I examine if the doggo ratings given out by @dog_rates (much responsibility) have an affect on how “liked” a tweet is
roba seria, Python e altro, anche se sembra lolloso
#:linguaggi di programmazione
::: drvinceknight

Elixir: pond, funzioni stateful e GenServer
argomento noto ma OK
#:programmazione funzionale
::: Grab the Blaster

Fork Commit Merge
#:open source
::: MadBob

“Chinese feminists found a way around [Weibo blocking #MeToo hash] they began using #RiceBunny in its place along w the rice bowl & bunny face emoji…the words for “rice bunny” are pronounced “mi tu,” a homophone that cleverly evades detection”
#:censura
::: jennyyangtv ::: sdallagata

Guida del Garante sull’applicazione del #GDPR, riassunto per i tecnici
#:Web, Internet
::: madbob

On the 20th anniversary of @mozilla, @stshank invites open source advocates like @joi to reflect on how the project helped to change the tech industry
#:open source
::: medialab ::: marcoscan

La mia risposta a Se Internet venisse ridisegnato da zero, quali miglioramenti si potrebbero apportare per migliorarlo? Ci sono difetti di progettazione che potrebbero essere risolti?
#:Web, Internet
::: misterakko

he full-text PDFs for the second volume of the The Art, Science, and Engineering of #Programming are now available
#:programming, codice, snippet
::: programmingconf

‘Thousands of Companies Are Spying On You’
#:sicurezza, spionaggio, virus
::: Slashdot

using #lang slideshow on @racketlang to make slide presentations
#:language Racket
::: asumu

don’t forget about pilosa Distributed roaring bitmaps in Go
#:programming, codice, snippet
::: mattjaffee

The three uses of types
#:programming, codice, snippet
::: TheMichaelBurge

OpenGL bindings for Bash
#:linguaggi di programmazione
::: cialunet

Atlanta Still Struggles To Recover From Ransomware Attack
#:sicurezza, spionaggio, virus
::: Slashdot

The new social networks you should join instead of Facebook, according to a Y Combinator partner
#:social media
::: Gianlucadfiore

HyperLogLog in Rust
#:linguaggi di programmazione
::: NP-Incompleteness

Finalmente tutto va nella direzione di una stretta sullo sfruttamento dei #bigdata. Meglio tardi che mai
#:economia #:sicurezza, spionaggio, virus
::: azuech

Facebook plans crackdown on ad targeting by email without consent
#:social media
::: fabiochiusi

Se anche Zuckerberg vende azioni Facebook
#:ditte
::: sole24ore

It interests me how “Haskell isn’t a practical language, Haskellers are ivory tower elitists
la stessa cosa che si dice da sempre del Lisp; ma a me piace anche se poi uso Python (e una volta il Fortran)
#:programmazione funzionale #:linguaggi di programmazione
::: argumatronic

Our Devices May Listen More Attentively, Patents Filed By Google and Amazon Suggest (nytimes.com)
#:privacy
::: Slashdot

New post (We have Stats) has been published on Remmina
#:Web, Internet
::: RemminaProject

Evidence for this? “scandals such as the Facebook data leak threaten to ‘subvert our democratic systems’”
#:caos informativo, fake news, bufale
::: fabiochiusi

The Facebook deactivation process might be the creepiest and most desperate in modern Internet
#:social media
::: wesmckinn

Duolingo To Silicon Valley Workers: Move To Pittsburgh, Where You Can Actually Afford a Home
#:economia
::: Slashdot

Python, wat
#:linguaggi di programmazione
::: peterseibel

my mini-manifesto on what’s to be done to avoid the next Facebook debacle
#:Web, Internet
::: evgenymorozov

Public broadcasters feel tension between their public service mandate and their reliance on platforms like Facebook
#:media #:social media
::: NiemanLab

Ubuntu Touch: La rinascita
#:dispositivi mobili
::: dcavedon

@LibreOffice change de logo ! L’occasion d’encourager quelques-uns de nos utilisateurs !
#:open source
::: LibreOfficeFR

An introduction to the Flask Python web app framework
#:linguaggi di programmazione
::: cialunet

Understanding Linux filesystems: ext4 and beyond
#:sistemi operativi
::: cialunet

I dati che Facebook ha di ciascuno di noi. E che non vende
#:privacy
::: valigiablu

Ora che è tutto finito in serenità come ci aspettavamo sarebbe il caso di fare un bel repulisti dei giornali che vi hanno tratto in inganno, non credete? Quando/se succederà per la ISS avremo bisogno di tutto il vostro aiuto e buon senso
#:media
::: AstronautiCAST

Use Musicbrainz to get CD information
#:tools, componenti software
::: cialunet

DNS Resolvers Performance compared
#:Web, Internet
::: marcelsalathe

Celebrating a Decade of Programming Historians
#:programming, codice, snippet
::: Adam_Crymble

Zuck envisions an independent appeal process for content on FB: “some sort of structure, almost like a Supreme Court, (…), who ultimately make the final judgment call on what should be acceptable speech”
#:protagonisti #:social media
::: fabiochiusi

1.1.1.1: Fast, privacy-first consumer DNS service
sarà mica un pesce d’aprile? No, pare sia OK
#:Web, Internet
::: newsycombinator ::: mhmtkcn ::: slashdot ::: TheHackersNews

We see many people #degoogle #deletefacebook over #easter! Good move
#:privacy
::: Nextclouders

History is full of massive harm done by people with great power who are utterly convinced that because they believe themselves to have good intentions, they cannot do harm or cause grave harm
#:sicurezza, spionaggio, virus #:protagonisti
::: zeynep

HTTP Cookies— PyMOTW 3
#:linguaggi di programmazione
::: doughellmann

Red Hat CEO Talks About State Of Open Source
#:open source
::: Slashdot

Fauxpersky: CredStealer malware written in AutoHotKey masquerades as Kaspersky Antivirus, spreading through infecting USB drives
#:sicurezza, spionaggio, virus
::: b3h3m0th

The End of Windows
#:sistemi operativi
::: rolandguelle

#Zuckerberg ci racconta della necessità di vendere i nostri dati per permettere l’accesso alle piattaforme digitali non solo ai ‘ricchi’. Questa è una delle più grandi bugie del loro business model: in questo modo si concorre a mantenere i poveri ancora più poveri
#:protagonisti
::: azuech

Java, Kotlin, Groovy, Clojure, Scala and others embrace different programing styles and paradigms. It’s amazing to consider the versistility of the JVM! We should celebrate the diversity of languages that our platform supports, not argue over which is better
#:linguaggi di programmazione
::: rmonson

Chrome Is Scanning Files on Your Computer, and People Are Freaking Out
#:sicurezza, spionaggio, virus
::: Slashdot

It’s worth noting Localytics and Apptimize aren’t data brokers; they are the kinds of companies app makers use to measure performance. That said, not clear they need such customer info
#:sicurezza, spionaggio, virus
::: inafried

Thread: The #CambridgeAnalytica #SCL scandal roils the world. Here are some stories from nations realizing SCL operated in their elections, and the ensuing distancing and denials
#:sicurezza, spionaggio, virus
::: profcarroll

Tor Winds Down Its Encrypted Messenger App 3 Years After Launch
#:Web, Internet
::: Slashdot

Zuckerberg On Facebook’s Role In Ethnic Cleansing In Myanmar: ‘It’s a Real Issue’
#:social media
::: Slashdot ::: EthanZ

Bring the language of supercomputers to your desktop with SimplyFortran, a modern Fortran development environment
#:linguaggi di programmazione
::: cialunet

Looking at all the global maps that I share you might’ve wondered why Central Africa is missing so often. This excellent article explains why “no data” is so common and argues that data is crucial in order to create a healthy wealthy stable Africa
#:dati, raccolta
::: simongerman600

Released the @nteractio extension for @ProjectJupyter! You can try it out on @mybinderteam now 😊
ancora tutto da fare (mi sembra)
#:linguaggi di programmazione
::: rgbkrk

Panerabread.com Leaks Millions of Customers Records
#:sicurezza, spionaggio, virus
::: Slashdot

Google’s decision to kill Google Reader was a turning point in enabling media to be manipulated by misinformation campaigns. The difference between individuals choosing the feeds they read & companies doing it for you affects all other forms of media
#:Web, Internet
::: anildash

UN: Facebook has turned into a beast in Myanmar
#:censura
::: marcelsalathe ::: tedeschini ::: fabiochiusi

If you want to understand the incompleteness of “If you’re not paying for the product, you’re the product,” just go to the movies. We spent $75 on four tickets yesterday and had to watch 35 minutes of ads
#:media #:ad, pubblicità
::: doctorow ::: jbenton

Instagram suddenly chokes off developers as Facebook chases privacy
#:social media
::: fabiochiusi

La libertà di espressione nell’era dei social network
#:social media
::: valigiablu

Facebook could actually benefit from a little regulation
#:social media
::: datatheism

10 commands every Linux user should know
#:sistemi operativi
::: cialunet

Catastrofismo giornalistico non richiesto
#:caos informativo, fake news, bufale
::: quantizzando

If you wonder “how can I contribute to OpenSource”, remember that the best thing you can do is to integrate missing documentation. And it doesn’t even require coding!
#:open source
::: thek3nger

The 1300+ page draft-ANSI-CL document as a nice PDF with sidebar
#:lisp(s)
::: RainerJoswig

The fake news campaign that failed – South Africa has a long history of racial tension. Three businessmen tried tapping into that with a fake news network for their own gain. It didn’t work
#:caos informativo, fake news, bufale
::: Info_Activism

Imagine millions if not billions of precisely tailored messages, including synthetic video, in future campaigns—all machine-generated. These tools are available now
#:media
::: fabiochiusi

Il cellulare compie 45 anni
#:storia
::: HDblog

“Twitter Users Unaware Posts are Used for Research”
#:social media
::: alondra

When it Comes To Privacy, Consent is Immaterial. Corporate and Gov’t Surveillance Systems Must Be Stopped Before They Ask For Consent: Richard Stallman
#:privacy
::: Slashdot

Do you want to know how to make functional code orthogonal? This presentation by @jdegoes introduces orthogonality and composability and how to make functional code orthogonal
#:programmazione funzionale
::: Signify_Tech

Schools Are Giving Up on Smartphone Bans
non so se sono solo io ma ultimamente vedo meno gente costantemente con il telefono in mano, forse ci si stanno abituando
#:dispositivi mobili
::: Slashdot

My @TIME op-ed in response to Facebook/Cambridge Analytica about how we need to fix the way we’re doing software if we want to get serious about regulating privacy
#:sicurezza, spionaggio, virus
::: jeanqasaur

Caso Skripal, una tragicommedia di portata globale
se la disinformazione viene da chi non ti aspetti; aspetta, non è la prima, sono recidivi
#:caos informativo, fake news, bufale
::: fabrizio_sitzia ::: robn1980 ::: fabrizio_sitzia

I took a step back and stopped trying to make Vim work like the other text editors I had used
#:tools, componenti software
::: ThePracticalDev

New C++ 2020 features
#:linguaggi di programmazione
::: CompSciFact

US Suspects Listening Devices in Washington
#:sicurezza, spionaggio, virus
::: Slashdot

Racket continues to have everything… here’s a procedural sound library
#:language Racket
::: dustyweb

Scoop: An internal white paper at Facebook shows in detail how Trump’s campaign was better at leveraging Facebook’s advertising tools than Clinton’s campaign
#:social media
::: sarahfrier

There’s currently multiple hoaxes going around about the YouTube shooting
#:social media
::: BuzzFeedNews ::: Slashdot ::: ilpost ::: guardiantech

Half of European Flights Delayed Due To System Failure
#:sicurezza, spionaggio, virus
::: Slashdot

Towards a Type System for Containers and AWS Lambda to Avoid Failures. Future of our industry right here. Seriously
#:programming, codice, snippet
::: bitemyapp

WhatsApp Public Groups Can Leave User Data Vulnerable To Scraping
#:sicurezza, spionaggio, virus
::: Slashdot

Su @wireditalia vi spieghiamo la Riforma Europea del #Copyright e il rischio di una #tassa europea sui #link con la scusa di salvare il giornalismo
#:media #:politica
::: VincenzoTiani

Facebook Blames a ‘Bug’ For Not Deleting Your Seemingly Deleted Videos
#:privacy
::: Slashdot

Did you know GitHub uses Haskell in production? It powers our Semantic Code analysis, and we’re looking for someone to join and lead the team
#:programmazione funzionale
::: reiddraper

Facebook CEO Says Not Planning To Extend European Privacy Law Globally
#:privacy
::: Slashdot ::: fabiochiusi

How the EU’s Copyright Reform Threatens Open Source–and How to Fight It
#:copyright e brevetti
::: Gianlucadfiore

Just found out about #NIM a statically typed and compiled programming language
#:linguaggi di programmazione
::: Alexintosh

The bots beat: How not to get punked by automation
#:social media
::: fabiochiusi

La diffusione delle notizie false su Twitter
#:social media
::: formicablu

We removed this latest set of Pages and accounts solely because they were controlled by the IRA — not based on the content
#:censura
::: fabiochiusi

Defend text and data mining in Europe
#:copyright e brevetti
::: CBlengio

R.Stallman: if the software in your computer is the non-free software of Apple, Google & Microsoft, it spies on you regularly
#:sicurezza, spionaggio, virus #:open source
::: MCPievatolo

Porting to Linux on Power: 5 tips that could turn a good port into a great port
#:sistemi operativi #:hardware
::: b3h3m0th

Let’s build Chuck Norris!
#:linguaggi di programmazione
::: b3h3m0th

Don’t know if this is the right tool but I’m definitely on board with the idea that bots ought to be clearly marked as possible on social media platforms
#:social media
::: Aelkus

Inoreader is my new favorite RSS reader
#:Web, Internet
::: JohnDCook

Outgoing White House Emails Not Protected by Verification System
#:sicurezza, spionaggio, virus
::: Slashdot

First draft of UNESCO #Internet universality indicators
#:Web, Internet
::: phisaz

An engineer installing an IBM computer, 1958
#:storia
::: TarakRindani

Cambridge Analytica May Have Had Facebook Data From 87 Million People
#:sicurezza, spionaggio, virus
::: Slashdot ::: marcelsalathe

McAfee Finds That Gamers Are Strong Candidates for Cybersecurity Jobs
#:programming, codice, snippet
::: Slashdot

Equity, creativity, and lifelong learning through #coding
#:programming, codice, snippet
::: medialab

A gentle introduction to #rustlang
#:linguaggi di programmazione
::: rustlang

I like to share the story of a critical security bug with you. Contrary to other issues in TLS/SSL, it’s a story with happy ending. Nobody was harmed. The bug was fixed before it affected the general population
#:linguaggi di programmazione #:bug
::: gvanrossum

Facebook’s Privacy Fixes Have Broken Tinder
#:sicurezza, spionaggio, virus
::: Slashdot

La dura legge della Malesia contro le “notizie false”
#:censura
::: hronir

Interesting statistics
#:Web, Internet
::: italovignoli

Should I post my own blog posts to r/ocaml, or should I be humble?
i blog non sono tutti morti
#:programming, codice, snippet
::: keleshev

Microsoft Touts Breakthrough In Making Chatbots More Conversational
#:Web, Internet
::: Slashdot

What is the Strict Aliasing Rule and Why do we care?
#:linguaggi di programmazione
::: shafikyaghmour

Computation of the 100 quadrillionth hexadecimal digit of π
#:programming, codice, snippet
::: johnregehr

Right. And by the same token: don’t fix Google, Amazon, Uber, Twitter – or the NyTimes. Replace them
#:Web, Internet
::: fabiochiusi

David Kirkpatrick says there should be an impartial external entity, possibly made up of United Nations representatives, to oversee and administrate Facebook
#:social media
::: mathewi

Mark did a Q&A with hundreds of reporters on a phone call today, here is the full transcript
#:social media
::: mosseri ::: fabiochiusi

Presenting research papers of the future ! One large @ProjectJupyter notebook with code embedded
#:linguaggi di programmazione
::: MeMohanty

Facebook ha sospeso per 2 giorni e mezzo @lucianocapone per questo post
#:social media
::: hronir

Who really owns an open project?
#:open source
::: cialunet

great page explaining methods overloading and overriding in java
#:linguaggi di programmazione
::: medeoTL

Getting started with Vagrant
#:programming, codice, snippet
::: cialunet

1977: Alice and Bob became a thing
#:storia
::: todayininfosec

Hi @NortonOnline the Norton Core is clearly running Linux and the license requires you to distribute the kernel source code so where can I get it?
#:open source
::: mjg59

for years the @EU_Commission has promoted #openscience and now it is willing to trow all those efforts under the bus in its ill-fated attempt to reform the EU copyright system
#:open source
::: communia_eu

next.js has made life so much easier. Till now i have created 4 websites and 1 electron app using it.
#:linguaggi di programmazione
::: ritz078

per un sito di news senza pubblicità pagherei al mese
#:media
::: emenietti

Così funziona il mercato della sorveglianza distribuita — Broker di dati, codici, tracciamenti, pagamenti: il sistema distribuito e interconnesso che ci segue online e offline (non solo #Facebook)
#:sicurezza, spionaggio, virus
::: carolafrediani

Wow, stealing credit card numbers over Bluetooth, and full PoC
#:pirateria
::: samykamkar

1.2 million accounts were suspended since August 2015 up until December 2017
#:social media
::: fabiochiusi

It was super fun to speak at @USAScienceFest to middle and high school students about programming, privacy, and why understanding software is one of the most important social problems of our time
#:privacy #:programming, codice, snippet
::: jeanqasaur

OS people already know that Multics already invented everything. It seems the security folks are just discovering this
#:storia #:sicurezza, spionaggio, virus
::: 0xabU

I added a video to a @YouTube playlist http://youtu.be/_BoMXcUa6C0?a Inclusive Design 2018-L01: Accessibilità web
ci sono tantissime cose on teh toobz 😁 queste lezioni se fossi ggiovane…
#:Web, Internet
::: fulcorno

Happy 20th birthday @Mozilla!
#:open source #:storia
::: MIT_CSAIL

Facebook Was in Talks With Top Hospitals Until Last Month To Share Data of Most Vulnerable Patients
#:sicurezza, spionaggio, virus
::: Slashdot

WARNING: @_tokenpay_ username is almost alike @tokenpay. @_tokenpay_ have 0 followers
#:sicurezza, spionaggio, virus
::: thatsascam

Excellent service: @thatsascam is a Twitter bot that replies to cryptoscam tweets, warning potential victims
#:sicurezza, spionaggio, virus
::: mikko

A Linux-kernel memory model!
#:sistemi operativi
::: johnregehr

Facebook says data on most of its 2 billion users could have been accessed improperly
#:sicurezza, spionaggio, virus
::: business

LibreOffice 6.0.3 has been released, with over 70 bugfixes
#:open source
::: letozaf

Online Gaming Could Be Stalled by Net Neutrality Repeal, ESA Tells Court
#:Web, Internet
::: Slashdot

Get a rundown of some of the new commandline tools that cloud-init 18.2 offers
#:tools, componenti software
::: cialunet

Google Fuchsia si può provare tramite browser web
#:sistemi operativi
::: HDblog

Discover the pioneers who paved the initial stretches of the long and winding road that led to modern MOS technology
#:storia
::: ComputerHistory

Secret Service Warns of Chip Card Scheme
#:pirateria
::: Slashdot

Motorola’s Modular Smartphone Dream Is Too Young To Die
#:hardware #:dispositivi mobili
::: Slashdot

We’re releasing a new version of Scratch in August 2018! Here are 3 things to know about Scratch 3.0
#:linguaggi di programmazione #:scuola, educazione
::: scratch

Zuckerberg touts a system to recognize messages to incite violence and stops them from going through in Myanmar. The “system” – actually, humans – reply there was no such thing
#:social media
::: fabiochiusi

Ma davvero Cambridge Analytica ha manipolato il voto usando i dati online degli utenti?
#:sicurezza, spionaggio, virus
::: valigiablu

These Messages Show Julian Assange Talked About Seeking Hacked Files From Guccifer 2.0
#:sicurezza, spionaggio, virus
::: fabiochiusi

Goofy learns to fish: Why good documentation matters
#:programming, codice, snippet
::: cialunet

Mainstream academia embraces open source hardware
#:open source #:hardware
::: cialunet

Our experience report on integrating software engineering key practices into an OOP Massive* In-Classroom Course
#:programming, codice, snippet
::: mtorchiano

Highlights and audio from Zuckerberg’s emotional Q&A on scandals
#:protagonisti
::: TechCrunch

Amazon ‘used neo-Nazi guards to keep immigrant workforce under
#:ditte
::: RadioProzac

Nell’incredibile intervista di Casaleggio al Sole, l’uomo solo al comando del grillismo dice: “Rousseau è un sistema che ci invidiano in tutto il mondo”
#:sicurezza, spionaggio, virus
::: claudiocerasa

Grazie @ilpost per chiudere i commenti esattamente quando inizia la polemica e non posso più ribattere
#:censura
::: Gianlucadfiore

I wonder what will be of the “mind reading” Facebook project introduced last year. Remember?
#:social media
::: fabiochiusi

Great article by @glynmoody on the impact on #freesoftware and #opensource of the forthcoming EU directive on copyright
#:copyright e brevetti
::: rdicosmo

La CDU di Angela Merkel e i liberali di FDP hanno comprato dalle Poste i dati microtargeting degli elettori durante la campagna 2017
#:sicurezza, spionaggio, virus
::: valigiablu

Per quelli che dicono che i debunker sono pilotati dai poteri forti o sono servi del governo: Butac.it sotto sequestro
#:censura #:caos informativo, fake news, bufale
::: disinformatico ::: emenietti ::: emenietti ::: thek3nger ::: RobiVil ::: cicap ::: ziozetti ::: ShooterHatesYou ::: butacit ::: fabiochiusi ::: DavidPuente ::: jacopogiliberto ::: cmnit ::: yoshi979 ::: M4xi3rrant ::: AngeloScaduto ::: BeppeGiulietti ::: AlbertoNardelli

Donald Knuth: “The Art of Computer Programming: Satisfiability and Combinatorics”
#:protagonisti
::: PaniczGodek

Breaking News
giornale di carta, quindi è una cosa seria!
#:media
::: valigiablu

Facebook’s Sheryl Sandberg Says There Were Likely Other Breaches Like Cambridge Analytica
#:sicurezza, spionaggio, virus
::: marcelsalathe

Russia Files Lawsuit To Block Telegram Messaging App
#:censura #:social media
::: Slashdot ::: adrianshahbaz

The Noisy Fallacies of Cambridge Analytica and Psychographic Targeting
#:sicurezza, spionaggio, virus
::: RadioProzac

The proposed Council compromise on #TDM is still not good enough. Needs to expand beneficiaries and scope of the exception
#:copyright e brevetti
::: communia_eu

It’s been about ten years since @codinghorror and I started building @StackOverflow so I decided to write a series of blog posts in retrospective!
una storia esemplare di come dovrebbe funzionare il web
#:programming, codice, snippet
::: spolsky

Italiani e social media nella ricerca di #Blogmeter. Ne esce fuori una fotografia dove la fruizione è prevalentemente di “superficie”. In questo senso, è allarmante la carenza di competenza sociale
#:social media
::: SergioGridelli

Interested in how developers use Python and related technologies? Check out #pythondevsurvey2017 Results
#:linguaggi di programmazione
::: jetbrains

ALGOL 68 would have been an improvement over most of its successors, had it had any
#:storia
::: tvdstorm

Facebook’s surveillance powers are nothing compared to what your Internet service provider is capable of
#:sicurezza, spionaggio, virus
::: BKCHarvard

In Italia almeno un quarto della popolazione non ha competenze digitali o non utilizza internet, ecco perché è strategico il ruolo dell’alfabetizzazione digitale a tutti i livelli e per tutte le età
#:Web, Internet #:economia
::: SergioGridelli

Last year Uk government has rejected one similar proposal from Google for his Deep Mind Health program. In 2016 the italian government led by Matteo Renzi has signed an agreement with IBM for the Watson Health Center, now in standby
#:sicurezza, spionaggio, virus
::: azuech ::: AntonioCasilli

12 Git tips for Git’s 12th birthday
#:open source
::: cialunet

Hey @twitterdev, I am one of the first million twitter users, and I will probably stop using Twitter altogether if you don’t #fixtwitter
#:social media
::: GavinBrown

Movie studios send takedown notices to Google, asking Google to take down the takedown notices
#:Web, Internet
::: mikkotweets2013

[Windows 10] Installare Windows Subsystem for Linux
#:sistemi operativi
::: Il nido del Picchio

what a difference a presidency makes. today’s @nytimes editorial correctly calls #fakenews “an ill-defined term that will put tremendous power in the hands of government officials to punish journalists and publishers”
#:caos informativo, fake news, bufale
::: davidakaye

Just released the first intentionally stable release of http://immutable.rs. It’s got all the important data structures now, in a state I’m satisfied with. I’ve got more goodies in the pipeline, but the API should be stable
#:linguaggi di programmazione
::: bodil

il video della mia sessione “Containers orchestration with Kubernetes and OpenShift” al meetup @devdayit
#:programming, codice, snippet
::: ppatierno

I received confirmation that data of up to 2.7 mln users in the EU could have been abused
#:sicurezza, spionaggio, virus
::: VeraJourova ::: VeraJourova

“Oblivious DNS: Plugging the Internet’s Biggest Privacy Hole”
#:Web, Internet
::: b3h3m0th

Here is my final list of 10 rules that I found helpful navigating a career, each as a short blog post
#:economia
::: marcelsalathe

Cryptography is why we have e-commerce: you can’t move credit card numbers without encryption. Trillions of dollars generated in new trade. But no central bank function, of course. This is just trade optimization
#:sicurezza, spionaggio, virus
::: leashless

Fun post on building IDE features into Excel
#:programming, codice, snippet
::: _wilfredh

Facebook e la guerra di potere
#:Web, Internet #:politica
::: CBlengio

Molti di voi ci hanno contattato per chiedere come poterci aiutare, così dopo una giornata di riflessione abbiamo deciso che sarebbe stupido da parte nostra non accettare le offerte di chi vuole darci una mano
#:censura
::: butacit

Haskell – 160 – IO, input/output – 4

Continuo da qui, copio qui, scrollare fino a “Exercises”.

esercizio
Write a program that first asks whether the user wants to read from a file, write to a file or quit. If the user responds quit, the program should exit. If he responds read, the program should ask him for a file name and print that file to the screen (if the file doesn’t exist, the program may crash). If he responds write, it should ask him for a file name and then ask him for text to write to the file, with “.” signaling completion. All but the “.” should be written to the file.

È una variante del programma fileread del post precedente; si può fare (cit.) 😁

Invece della mia versione vado alla soluzione perché più completa con varianti e spiegazioni.

The code might look something like (si sono rese necessarie un paio di modifiche negli imports iniziali):

rw.hs

import System.IO
import Control.Exception

main = do
  hSetBuffering stdin LineBuffering
  putStrLn "Do you want to [read] | [write] | [quit] a file, ...?"
  cmd <- getLine 
  case cmd of 
    "quit" -> do putStrLn ("Goodbye!")
                 return ()
    "read"  -> do doRead; main
    "write" -> do doWrite; main
    _       -> do putStrLn
                    ("I don't understand the command "
                     ++ cmd ++ ".")
                  main

doRead = do
  putStrLn "Enter a file name to read:"
  fn <- getLine 
  bracket (openFile fn ReadMode) hClose 
          (\h -> do txt <- hGetContents h
                    putStrLn txt)

doWrite = do
  putStrLn "Enter a file name to write:"
  fn <- getLine 
  bracket (openFile fn WriteMode) hClose 
          (\h -> do putStrLn
                      "Enter text (dot on a line by itself to end):"
                    writeLoop h)

writeLoop h = do
  l <- getLine
  if l == "."
    then return ()
    else do hPutStrLn h l
            writeLoop h

Compilo e lancio:

$ ghc -o rw rw.hs
[1 of 1] Compiling Main             ( rw.hs, rw.o )
Linking rw ...
$ ./rw
Do you want to [read] | [write] | [quit] a file, ...?
write
Enter a file name to write:
rw-test
Enter text (dot on a line by itself to end):
prova di
scrittura
su file.
.
Do you want to [read] | [write] | [quit] a file, ...?
read
Enter a file name to read:
rw-test
prova di
scrittura
su file.

Do you want to [read] | [write] | [quit] a file, ...?
quit
Goodbye!

The only interesting things here are the calls to bracket, which ensure the that the program lives on, regardless of whether there’s a failure or not; and the writeLoop function. Note that we need to pass the handle returned by openFile (through bracket to this function, so it knows where to write the input to).

Alternatively, we can make a version with readFile and writeFile that doesn’t use bracket:

doRead = do
  putStrLn "Enter a file name to read:"
  fn <- getLine

  txt <- readFile fn
  putStr txt

doWrite = do
  putStrLn "Enter a file name to write:"
  fn <- getLine
  txt <- getWriteLines
  writeFile fn txt

getWriteLines = do
  l <- getLine
  if l == "."
    then return ""
    else do lines <- getWriteLines
            return (line++"\n"++lines)

👽

Haskell – 159 – IO, input/output – 3

Continuo da qui, copio qui.

Programma: leggere un file
We can write a simple program that allows a user to read and write files. The interface is admittedly poor, and it does not catch all errors (try reading a non-existent file). Nevertheless, it should give a fairly complete example of how to use IO. Enter the following code into “FileRead.hs,” and compile/run:

FileRead.hs

module Main
    where

import System.IO
import Control.Exception

main = do
  hSetBuffering stdin LineBuffering
  doLoop

doLoop = do
  putStrLn "Enter a command rFN wFN or q to quit:"
  command <- getLine case command of 'q':_ -> return ()
    'r':filename -> do putStrLn ("Reading " ++ filename)
                       doRead filename
                       doLoop
    'w':filename -> do putStrLn ("Writing " ++ filename)
                       doWrite filename
                       doLoop
    _            -> doLoop

doRead filename =
  bracket (openFile filename ReadMode) hClose
          (\h -> do contents <- hGetContents h
                    putStrLn "The first 100 chars:"
                    putStrLn (take 100 contents))

doWrite filename = do
  putStrLn "Enter text to go into the file:"
  contents <- getLine 
  bracket (openFile filename WriteMode) hClose 
          (\h -> hPutStrLn h contents)

Lo compilo:

$ ghc -o fileread FileRead.hs
[1 of 1] Compiling Main             ( FileRead.hs, FileRead.o )
Linking fileread ...

$ ls -l fileread
-rwxr-xr-x 1 juhan juhan 1123488 apr  5 09:39 fileread

What does this program do? First, it issues a short string of instructions and reads a command. It then performs a case switch on the command and checks first to see if the first character is a ‘q.’ If it is, it returns a value of unit type.

Note: The return function is a function that takes a value of type a and returns an action of type IO a. Thus, the type of return () is IO ().

If the first character of the command wasn’t a ‘q,’ the program checks to see if it was an ‘r‘ followed by some string that is bound to the variable filename. It then tells you that it’s reading the file, does the read and runs doLoop again. The check for ‘w‘ is nearly identical. Otherwise, it matches _, the wildcard character, and loops to doLoop.

The doRead function uses the bracket function to make sure there are no problems reading the file. It opens a file in ReadMode, reads its contents and prints the first 100 characters (the take function takes an integer n and a list and returns the first n elements of the list).

The doWrite function asks for some text, reads it from the keyboard, and then writes it to the file specified.

Note: Both doRead and doWrite could have been made simpler by using readFile and writeFile, but they were written in the extended fashion to show how the more complex functions are used.

Lo provo

$ ./fileread
Enter a command rFN wFN or q to quit:
rfr-test
Reading fr-test
The first 100 chars:
test per
fileread
eseguibile ottenuto compilando FileRead.hs

Enter a command rFN wFN or q to quit:
wfr-scrivo
Writing fr-scrivo
Enter text to go into the file:
adesso provo

Enter a command rFN wFN or q to quit:
scrivo
Enter a command rFN wFN or q to quit:
leggo
Enter a command rFN wFN or q to quit:
q

OK, funziona.

The only major problem with this program is that it will die if you try to read a file that doesn’t already exists or if you specify some bad filename like *\^\#_@. You may think that the calls to bracket in doRead and doWrite should take care of this, but they don’t. They only catch exceptions within the main body, not within the startup or shutdown functions (openFile and hClose, in these cases). We would need to catch exceptions raised by openFile, in order to make this complete.
We will do this when we talk about exceptions in more detail in the section on Exceptions
[prossimamente].

👽

AI, innovazioni e blockchain – 16

IL Web è pieno di novità, mi sfuggono quasi tutte, ho intercettato solo queste 😋
Un caloroso ringraziamento a 💥 Natangelo, rockz! 💥

Can an improved peer review process help the computing community take responsibility for the problems we have caused?
#:programming, codice, snippet
::: ACM_FCA

La #PA italiana è davvero pronta a cavalcare l’onda dell’#IntelligenzaArtificiale?
#:artificial intelligence
::: TechEcon

81% of Recent ICOs Were Scams, Research Finds
#:economia
::: Slashdot

Reddit No Longer Accepts Bitcoin
#:blockchain e crypto*
::: Slashdot

Bitcoin, la metafora di Internet
mooolto interessante
#:blockchain e crypto*
::: marcodelmastro

FCC Authorizes SpaceX’s Ambitious Satellite Internet Plans
#:Web, Internet
::: Slashdot ::: emenietti

Hedge funder John Thompson: Tesla is ‘on the verge of bankruptcy’
pesce d’aprile precoce?
#:innovazioni, futuro
::: checovenier

Intel Files Patent For Energy-Efficient Bitcoin Mining Hardware
mi ricorda Sun che passò out of the blue dalle workstations grafiche ai servers Web
#:hardware #:blockchain e crypto*
::: Slashdot

AI Tool, Which Has Digested Nearly Every Reaction Ever Performed, Can Invent New Ways To Create Complex Molecules
#:artificial intelligence
::: Slashdot

Waymo Starts To Eclipse Uber in Race To Self-Driving Taxis
#:automazione
::: Slashdot

Why Every Bitcoin Fan Should be Excited About Schnorr Signatures
chissà cos’è? funziona?
#:blockchain e crypto*
::: theonevortex

How banks are using Blockchain
#:umorismo
::: Blockchainlife

Macron Wants Europe to Forget Facebook Fears and Embrace A.I. Good luck with that. Any “AI for Good” Initiative that has Facebook on board has zero credibility
#:artificial intelligence #:social media
::: marcelsalathe ::: Slashdot

Is It Illegal to Trick a Robot?
#:automazione
::: Slashdot

#Bitcoin is threatening to destroy the ability of governments to manipulate their own currencies, as the cryptocurrency creates a new way to evade official controls and move money across borders
#:blockchain e crypto*
::: Schuldensuehner

cointop – coin tracking for hackers
#:blockchain e crypto*
::: Gianlucadfiore

Why Robots Won’t Kill Jobs: The World’s Largest Robotics Company Says More Robots Means More Jobs
#:robots
::: Floridi

The trolley problem is useful as a distraction from the real problems of self-driving cars
#:automazione
::: NoelSharkey

Start of Go’s native blockchain support in the standard library, starting with os
#:blockchain e crypto*
::: bradfitz

Non-Tech Businesses Are Beginning To Use AI at Scale
#:artificial intelligence
::: Slashdot

Liechtenstein To Support #blockchain With New Regulations
#:blockchain e crypto*
::: thomaspower

Il titolo è di effetto, il panorama è un po’ più complicato #commercio – Effetto Amazon 10 mila posti a rischio
#:innovazioni, futuro #:economia
::: sdallagata

ROBOTS are distraction. Real problem for JOBS (& wages) is high PROFITS (profit/wage ratio at record level) not REINVESTED into economy
#:robots
::: MazzucatoM

I have ~5 minutes to explain to an audience for a class on “Blockchain” at Berkeley why it is total bullshit. I didn’t go easy
#:blockchain e crypto*
::: ncweaver

Apple plans to replace Intel processors with its own by 2020
#:innovazioni, futuro
::: Gianlucadfiore ::: greghendershott ::: emenietti

General versus domain intelligence
#:artificial intelligence
::: Daniel Lemire

Ce li spiega un linguista computazionale
le previsioni riguardo il futuro… (inizio-cit.)
#:artificial intelligence
::: wireditalia

Military Documents Reveal How the US Army Plans To Deploy AI In Future Wars
#:artificial intelligence
::: Slashdot

Microsoft has just released an Artificial Intelligence learning track, open for everyone
#:artificial intelligence
::: simona_cotin

olvidaron entrecomillar la dirección de Ethereum (una serie de letras y números) donde debían recibir el dinero y JavaScript, el lenguaje de programación usado, lo interpretó de otra manera
#:blockchain e crypto*
::: _rubenfa

Amazon sold over 80% of all toys sold online in USA. And over 90% of all sport & fitness gear
#:innovazioni, futuro
::: mikko

Google is splitting A.I. into its own business unit and shaking up its search leadership
#:artificial intelligence
::: emenietti

#Transumanesimo Ho fatto un tema in 4a liceo su questo (provando a essere visionario obviously)
#:innovazioni, futuro
::: piraflappy

Libpull: aggiornamenti sicuri per dispositivi IoT
L’IoT sta rendendo “smart” gli oggetti della nostra vita, integrando in essi l’intelligenza necessaria per interagire con noi e con l’ambiente che ci circonda.
niente panico per il video: ci sono 2min+15sec iniziali vuoti poi parte & rockz!
#:Internet of things
::: nexa ::: You Tube

Trump preparing to launch a war on Amazon
#:innovazioni, futuro
::: gabrielsherman

The blockchain is a technology for accounting under the condition of deep social distrust
#:blockchain e crypto*
::: stalfel

Swedes turn against cashlessness
#:innovazioni, futuro
::: marcelsalathe

Ethereum Founder Confronts Self-Proclaimed Bitcoin Creator Craig Wright, Calls Him a Fraud
#:blockchain e crypto*
::: Slashdot

The value of digital scarcity in an ever increasing digital world
#:blockchain e crypto*
::: enconconsulting

The growth rates of IoT, Cloud, Big Data & AI are unprecedented in the history of information technology
#:Internet of things
::: RichRogersIoT

Apple Hires Google’s AI Chief
#:artificial intelligence
::: Slashdot

Introducing Norman from Lab researcher @PINguAR: the world’s first algorithmically disturbed #AI
#:artificial intelligence
::: medialab

When you have highly valuable, completely virtual and almost entirely untraceable currency, there will naturally be a lot of theft
#:blockchain e crypto*
::: mikkotweets2013

Google Workers Urge CEO To Pull Out of Pentagon AI Project
#:artificial intelligence
::: Slashdot ::: L_badikho

The 3 Tricks That Made AlphaGo Zero Work
#:deep learning
::: MikeTamir

Will Artificial Intelligence Make Us Less Free? An ACLU blog series
#:artificial intelligence
::: benwizner

#AngeloFiora: il tornio con cui ho iniziato a lavorare è stato sostituito da un robot che ho imparato a programmare e mi ha privato dei momenti più noiosi e faticosi di carico e scarico #industry4.0
#:robots
::: BentivogliMarco

New MIT wearable lets users silently converse with it using electrodes that detect internal verbalization
#:innovazioni, futuro
::: MIT_CSAIL ::: medialab

One of Estonia’s First ‘e-Residents’ Explains What It Means To Have Digital Citizenship
#:innovazioni, futuro
::: Slashdot

Casaleggio vuole implementare Rousseau con la tecnologia blockchain, ma i registri distribuiti funzionano x i sistemi di voto?
#:blockchain e crypto*
::: gabriella_roux

AI Experts Boycott South Korean University Over ‘Killer Robots’
#:robots
::: Slashdot

Python, le liste e i cicli for (e non riesco mai a ricordarmi)

Yep! proprio così. Ci sono delle cose che anche se ti sono già capitate (a me più volte) e finanche se te l’hanno già detto (a me più volte) non riesci a ricordartele. O capita solo a me? Oggi voglio scrivere di una di queste così me ne ricorderò. O se me lo faranno notare quando mi capiterà potrò dire “lo so; l’ho anche scritto, qui!”.

Non so voi ma alle volte la bontà di un’elaborazione (un run) viene valutata da un valore finale o la forma di una linea (o un punto) su un grafico. O sono solo io? A volte il valore finale non cambia al cambiare dei dati di input o il grafico è subito esatto o sempre sbagliato… Ecco parlo di uno di quei casi.

È una cosa semplice, la sanno tutti (anch’io) e nell’esempio qui sotto si vede subito dov’è il bug ma in un programma vero, scritto come al solito non è immediatamente evidente e bisogna andarlo a stanare. E (o capita solo a me?) i propri errori sono quelli che sono i più nascosti. Ma basta con l’intro giustificativa inizio.

Uno script se non limitato a poche righe sarà organizzato in funzioni, che possono poi essere contenute in classi. Mi occuperò solo delle funzioni, ecco quad() una funzione elementare per fare il quadrato di un numero:

def quad(n):
  return n * n

Funziona proprio come ci si aspetta (uso la REPL):

$ python3 -q
>>> def quad(n):
...   return n * n
...
>>> i = 5
>>> q = quad(i)
>>> q
25
>>> i
5

quad(), essendo Python un tipper ducko fa più di quel che si pensa:

>>> type(i)
<class 'int'>
>>> type(q)
<class 'int'>
>>> f = 4.2
>>> r = quad(f)
>>> r
17.64
>>> type(f)
<class 'float'>
>>> type(r)
<class 'float'>

In ogni caso i parametri (i e f) vengono passati per valore. Ecco una versione ridondante, con print di debug; tipo di istruzioni che possono capitare se la funzione è complessa e si è pasticcioni:

def quadp(n):
  n *= n
  print("dentro", n)
  return n

Vediamola in azione:

>>> n = 8
>>> s = quadp(n)
dentro 64
>>> s
64
>>> n
8

OK! una cosa simile capita con le stringhe:

>>> def up(st):
...   return st.upper()
...
>>> st = 'ciao!'
>>> us = up(st)
>>> st
'ciao!'
>>> us
'CIAO!'

ho barato: ho applicato a st il metodo upper() che non la modifica ma ne crea una copia. Se modifico st nella funzione ottengo:

>>> def upm(st):
...   st = st.upper()
...   print("dentro", st)
...   return st
...
>>> st
'ciao!'
>>> us = upm(st)
dentro CIAO!
>>> us
'CIAO'
>>> st
'ciao!'

Tutto come previsto.

E le liste? In Python le liste vengono usate (anche?) al posto degli arrays; e funzionano bene.

Ecco lsquad(), restituisce la lista dei quadrati degli elementi della lista passata.

>>> def lsquad(ls):
...   ls = [ls[n] * ls[n] for n in range (len(ls))]
...   return ls
...
>>> lorig = [1, 2, 3, 4]
>>> lq = lsquad(lorig)
>>> lq
[1, 4, 9, 16]
>>> lorig
[1, 2, 3, 4]

OK, ma io che sono vecchio, più vecchio della list comprehension a  volte  spesso scrivo così:

>>> def lsfq(ls):
...   for n in range(len(ls)):
...     ls[n] = ls[n] * ls[n]
...   return ls
...
>>> lorig
[1, 2, 3, 4]
>>> lq = lsfq(lorig)
>>> lq
[1, 4, 9, 16]
>>> lorig
[1, 4, 9, 16]

OOPS! con il ciclo for la stringa passata è stata aggiornata!

E chiamate successive producono questo effetto:

>>> lq = lsfq(lorig)
>>> lorig
[1, 16, 81, 256]
>>> lq = lsfq(lorig)
>>> lorig
[1, 256, 6561, 65536]

Mi suggeriscono (tra le altre cose) questa variante, con costruzione di una nuova lista (rl):

def lstq(ls):
  rl = []
  for n in ls:
    rl.append(n * n)
  return rl

È OK ma sono sempre per la list comprehension. Forse solo questione di gusti.
CMQ, panico? No, c’è tutto scritto nella documentazione. E adesso anche qui.

E poi, se vi ricordate anche il C… (quella cosa del puntatore all’elemento iniziale dell’array, o ricordo male?) 😉

Oh! post è già stato aggiornato (due volte) in bozza prima ancora di essere pubblicato nel blog. E chissà se adesso è OK.

👽

Haskell – 158 – IO, input/output – 2

Continuo da qui, copio qui.

La libreria IO
The IO Library (available by importing the System.IO module) contains many definitions, the most common of which are listed below:

data IOMode  = ReadMode   | WriteMode
             | AppendMode | ReadWriteMode

openFile     :: FilePath -> IOMode -> IO Handle
hClose       :: Handle -> IO ()

hIsEOF       :: Handle -> IO Bool

hGetChar     :: Handle -> IO Char
hGetLine     :: Handle -> IO String
hGetContents :: Handle -> IO String

getChar      :: IO Char
getLine      :: IO String
getContents  :: IO String

hPutChar     :: Handle -> Char -> IO ()
hPutStr      :: Handle -> String -> IO ()
hPutStrLn    :: Handle -> String -> IO ()

putChar      :: Char -> IO ()
putStr       :: String -> IO ()
putStrLn     :: String -> IO ()

readFile     :: FilePath -> IO String
writeFile    :: FilePath -> String -> IO ()

bracket      ::
    IO a -> (a -> IO b) -> (a -> IO c) -> IO c

Note: The type FilePath is a type synonym for String. That is, there is no difference between FilePath and String. So, for instance, the readFile function takes a String (the file to read) and returns an action that, when run, produces the contents of that file. See the section on Synonyms [prossimamente] for more about type synonyms.

Most of these functions are self-explanatory. The openFile and hClose functions open and close a file, respectively, using the IOMode argument as the mode for opening the file. hIsEOF tests for end-of file. hGetChar and hGetLine read a character or line (respectively) from a file. hGetContents reads the entire file. The getChar, getLine and getContents variants read from standard input. hPutChar prints a character to a file; hPutStr prints a string; and hPutStrLn prints a string with a newline character at the end. The variants without the h prefix work on standard output. The readFile and writeFile functions read an entire file without having to open it first.

The bracket function is used to perform actions safely. Consider a function that opens a file, writes a character to it, and then closes the file. When writing such a function, one needs to be careful to ensure that, if there were an error at some point, the file is still successfully closed. The bracket function makes this easy. It takes three arguments: The first is the action to perform at the beginning. The second is the action to perform at the end, regardless of whether there’s an error or not. The third is the action to perform in the middle, which might result in an error. For instance, our character-writing function might look like:

writeChar :: FilePath -> Char -> IO ()
writeChar fp c =
  bracket
    (openFile fp ReadMode)
    hClose
    (\h -> hPutChar h c)

This will open the file, write the character and then close the file. However, if writing the character fails, hClose will still be executed, and the exception will be reraised afterwards. That way, you don’t need to worry too much about catching the exceptions and about closing all of your handles.

👽

Haskell – 157 – IO, input/output – 1

Continuo da qui, copio qui.

As we mentioned earlier, it is difficult to think of a good, clean way to integrate operations like input/output into a pure functional language. Before we give the solution, let’s take a step back and think about the difficulties inherent in such a task.

Any IO library should provide a host of functions, containing (at a minimum) operations like:

  • print a string to the screen
  • read a string from a keyboard
  • write data to a file
  • read data from a file

There are two issues here. Let’s first consider the initial two examples and think about what their types should be. Certainly the first operation (I hesitate to call it a “function”) should take a String argument and produce something, but what should it produce? It could produce a unit (), since there is essentially no return value from printing a string. The second operation, similarly, should return a String, but it doesn’t seem to require an argument.

We want both of these operations to be functions, but they are by definition not functions. The item that reads a string from the keyboard cannot be a function, as it will not return the same String every time. And if the first function simply returns () every time, there should be no problem with replacing it with a function f _ = (), due to referential transparency. But clearly this does not have the desired effect.

La soluzione RealWorld
In a sense, the reason that these items are not functions is that they interact with the “real world.” Their values depend directly on the real world. Supposing we had a type RealWorld, we might write these functions as having type:

printAString :: RealWorld -> String -> RealWorld
readAString  :: RealWorld -> (RealWorld, String)

That is, printAString takes a current state of the world and a string to print; it then modifies the state of the world in such a way that the string is now printed and returns this new value. Similarly, readAString takes a current state of the world and returns a new state of the world, paired with the String that was typed.

This would be a possible way to do IO, though it is more than somewhat unwieldy. In this style (assuming an initial RealWorld state were an argument to main), our “Name.hs” program from the section on Interactivity would look something like:

main rW =
  let rW' = printAString rW "Please enter your name: "
      (rW'',name) = readAString rW'
  in  printAString rW''
          ("Hello, " ++ name ++ ", how are you?")

This is not only hard to read, but prone to error, if you accidentally use the wrong version of the RealWorld. It also doesn’t model the fact that the program below makes no sense:

main rW =
  let rW' = printAString rW "Please enter your name: "
      (rW'',name) = readAString rW'
  in  printAString rW'                 -- OOPS!
          ("Hello, " ++ name ++ ", how are you?")

In this program, the reference to rW'' on the last line has been changed to a reference to rW'. It is completely unclear what this program should do. Clearly, it must read a string in order to have a value for name to be printed. But that means that the RealWorld has been updated. However, then we try to ignore this update by using an “old version” of the RealWorld. There is clearly something wrong happening here.

Suffice it to say that doing IO operations in a pure lazy functional language is not trivial.

Azioni
The breakthrough for solving this problem came when Phil Wadler realized that monads would be a good way to think about IO computations. In fact, monads are able to express much more than just the simple operations described above; we can use them to express a variety of constructions like concurrence, exceptions, IO, non-determinism and much more. Moreover, there is nothing special about them; they can be defined within Haskell with no special handling from the compiler (though compilers often choose to optimize monadic operations).

As pointed out before, we cannot think of things like “print a string to the screen” or “read data from a file” as functions, since they are not (in the pure mathematical sense). Therefore, we give them another name: actions. Not only do we give them a special name, we give them a special type. One particularly useful action is putStrLn, which prints a string to the screen. This action has type:

putStrLn :: String -> IO ()

As expected, putStrLn takes a string argument. What it returns is of type IO (). This means that this function is actually an action (that is what the IO means). Furthermore, when this action is evaluated (or “run”) , the result will have type ().

Note: Actually, this type means that putStrLn is an action within the IO monad, but we will gloss over this for now.

You can probably already guess the type of getLine:

getLine :: IO String

This means that getLine is an IO action that, when run, will have type String.

The question immediately arises: “how do you ‘run’ an action?”. This is something that is left up to the compiler. You cannot actually run an action yourself; instead, a program is, itself, a single action that is run when the compiled program is executed. Thus, the compiler requires that the main function have type IO (), which means that it is an IO action that returns nothing. The compiled code then executes this action.

However, while you are not allowed to run actions yourself, you are allowed to combine actions. In fact, we have already seen one way to do this using the do notation (how to really do this will be revealed in the chapter Monads). Let’s consider the original name program:

main = do
  hSetBuffering stdin LineBuffering
  putStrLn "Please enter your name: "
  name <- getLine
  putStrLn ("Hello, " ++ name ++ ", how are you?")

We can consider the do notation as a way to combine a sequence of actions. Moreover, the <- notation is a way to get the value out of an action. So, in this program, we’re sequencing four actions: setting buffering, a putStrLn, a getLine and another putStrLn. The putStrLn action has type String -> IO (), so we provide it a String, so the fully applied action has type IO (). This is something that we are allowed to execute.

The getLine action has type IO String, so it is okay to execute it directly. However, in order to get the value out of the action, we write name <- getLine, which basically means “run getLine, and put the results in the variable called name.”

Normal Haskell constructions like if/then/else and case/of can be used within the do notation, but you need to be somewhat careful. For instance, in our “guess the number” program, we have:

  do ...
     if (read guess)  num
              then do putStrLn "Too high!"
                      doGuessing num
              else do putStrLn "You Win!"

If we think about how the if/then/else construction works, it essentially takes three arguments: the condition, the “then” branch, and the “else” branch. The condition needs to have type Bool, and the two branches can have any type, provided that they have the same type. The type of the entire if/then/else construction is then the type of the two branches.

In the outermost comparison, we have (read guess) < num as the condition. This clearly has the correct type. Let’s just consider the “then” branch. The code here is:

                    do putStrLn "Too low!"
                       doGuessing num

Here, we are sequencing two actions: putStrLn and doGuessing. The first has type IO (), which is fine. The second also has type IO (), which is fine. The type result of the entire computation is precisely the type of the final computation. Thus, the type of the “then” branch is also IO (). A similar argument shows that the type of the “else” branch is also IO (). This means the type of the entire if/then/else construction is IO (), which is just what we want.

Note: In this code, the last line is else do putStrLn "You Win!". This is somewhat overly verbose. In fact, else putStrLn "You Win!" would have been sufficient, since do is only necessary to sequence actions. Since we have only one action here, it is superfluous.

It is incorrect to think to yourself “Well, I already started a do block; I don’t need another one,” and hence write something like:

    do if (read guess) < num
         then putStrLn "Too low!"
              doGuessing num
         else ...

Here, since we didn’t repeat the do, the compiler doesn’t know that the putStrLn and doGuessing calls are supposed to be sequenced, and the compiler will think you’re trying to call putStrLn with three arguments: the string, the function doGuessing and the integer num. It will certainly complain (though the error may be somewhat difficult to comprehend at this point).

We can write the same doGuessing function using a case statement. To do this, we first introduce the Prelude function compare, which takes two values of the same type (in the Ord class) and returns one of GT, LT, EQ, depending on whether the first is greater than, less than or equal to the second.

doGuessing num = do
  putStrLn "Enter your guess:"
  guess  do putStrLn "Too low!"
             doGuessing num
    GT -> do putStrLn "Too high!"
             doGuessing num
    EQ -> putStrLn "You Win!"

Here, again, the dos after the ->s are necessary on the first two options, because we are sequencing actions.

If you’re used to programming in an imperative language like C or Java, you might think that return will exit you from the current function. This is not so in Haskell. In Haskell, return simply takes a normal value (for instance, one of type Int) and makes it into an action that returns the given value (for instance, the value of type IO Int). In particular, in an imperative language, you might write this function as:

void doGuessing(int num) {
  print "Enter your guess:";
  int guess = atoi(readLine());
  if (guess == num) {
    print "You win!";
    return ();
  }

  // we won't get here if guess == num
  if (guess < num) {
    print "Too low!";
    doGuessing(num);
  } else {
    print "Too high!";
    doGuessing(num);
  }
}

Here, because we have the return () in the first if match, we expect the code to exit there (and in most imperative languages, it does). However, the equivalent code in Haskell, which might look something like:

doGuessing num = do
  putStrLn "Enter your guess:"
  guess  do putStrLn "You win!"
             return ()

  -- we don't expect to get here unless guess == num
  if (read guess < num)
    then do putStrLn "Too low!";
            doGuessing num
    else do putStrLn "Too high!";
            doGuessing num

will not behave as you expect. First of all, if you guess correctly, it will first print “You win!,” but it won’t exit, and it will check whether guess is less than num. Of course it is not, so the else branch is taken, and it will print “Too high!” and then ask you to guess again.

On the other hand, if you guess incorrectly, it will try to evaluate the case statement and get either LT or GT as the result of the compare. In either case, it won’t have a pattern that matches, and the program will fail immediately with an exception.

esercizi
Write a program that asks the user for his or her name. If the name is one of Simon, John or Phil, tell the user that you think Haskell is a great programming language. If the name is Koen, tell them that you think debugging Haskell is fun (Koen Classen is one of the people who works on Haskell debugging); otherwise, tell the user that you don’t know who he or she is.

Write two different versions of this program, one using if statements, the other using a case statement.

Using if, we get something like:

main = do
  hSetBuffering stdin LineBuffering
  putStrLn "Please enter your name:"
  name <- getLine
  if name == "Simon" || name == "John" || name == "Phil"
    then putStrLn "Haskell is great!"
    else if name == "Koen"
           then putStrLn "Debugging Haskell is fun!"
           else putStrLn "I don't know who you are."

Note that we don’t need to repeat the dos inside the ifs, since these are only one action commands.

We could also be a bit smarter and use the elem command which is built in to the Prelude:

main = do
  hSetBuffering stdin LineBuffering
  putStrLn "Please enter your name:"
  name <- getLine
  if name `elem` ["Simon", "John", "Phil"]
    then putStrLn "Haskell is great!"
    else if name == "Koen"
           then putStrLn "Debugging Haskell is fun!"
           else putStrLn "I don't know who you are."

Of course, we needn’t put all the putStrLns inside the if statements. We could instead write:

main = do
  hSetBuffering stdin LineBuffering
  putStrLn "Please enter your name:"
  name <- getLine
  putStrLn
    (if name `elem` ["Simon", "John", "Phil"]
       then "Haskell is great!"
       else if name == "Koen"
              then "Debugging Haskell is fun!"
              else "I don't know who you are.")

Using case, we get something like:

main = do
  hSetBuffering stdin LineBuffering
  putStrLn "Please enter your name:"
  name  putStrLn "Haskell is great!"
    "John"  -> putStrLn "Haskell is great!"
    "Phil"  -> putStrLn "Haskell is great!"
    "Koen"  -> putStrLn "Debugging Haskell is fun!"
    _       -> putStrLn "I don't know who you are."

Which, in this case, is actually not much cleaner.

Nota: Hal dimentica di dirmi che devo importare la libreria di IO:

import System.IO

👽

cit. & loll – 90

Oggi è il giorno che tutti aspettano: un’altra puntata cit.osa e lollosa, eccola 😋

I’d like to see a “slow information” movement, parallel to the “slow food” movement. Just little things. Read whole articles, don’t skim. Read more books. Have commentary be a small part of your intake. In short– more protein and fiber, less cake
::: ZachWeiner

Everything that moves
::: think_parallel

Where innovation is a concern, small teams with a purpose crush large teams with a process
::: RichRogersIoT

Software development should be thought of as a cycle of continual learning
::: RichRogersIoT

It me! ⚡️ “What would happen if a programmer and a product manager had to cut down a tree?”
la versione estesa di Peter; anche lui fa rassegne come me (meglio di me)?
::: peterseibel

just realized the “projects” page on my website was hilariously out of date and kind of embarrassing (“hi here is my first javascript project from 2012”)
::: b0rk

When you lied on your CV about having previous sheepdog experience
::: BoringEnormous

This is a terrifying narrative
::: SarahJamieLewis

I wouldn’t be too worried if Facebook knew who I called or sent messages to
::: martijn_grooten

20+ years coding and I still check
::: KiwiCoder

Say what you will about modern C++, it’s great at providing solutions to the problems
::: jckarter

This photo nicely captures what one of the smarter AI systems sees in us
::: RosalindPicard

My husband’s ingenious idea
::: oliviasolon

Con i vostri dati #Zuckerberg è diventato così ricco
::: Santas_Official

New rule: Tagging questions on Stack Overflow
::: lizardbill

foreground and background process
::: JenMsft

Best ending of a book ever
::: marcelsalathe

Russian embassy mentioning Lovecraft and [Cthulhu’s] tentacles is the best Cold War tweet ever!
::: fabrizio_sitzia

Things developer say
::: RichRogersIoT

Code review that takes place in a browser isn’t just more inconvenient, it’s often shallower, too
::: jordwalke

We do not collect and sell our customers’
::: JonyIveParody

This becomes less and less surprising once you learn
::: asmeurer

Twitter, je sais que tu peux faire des miracles alors voila
::: GollumPrecieux

Problem solved!
::: volatile_void

My father give me the greatest gift
::: RichRogersIoT

every tech ceo guy ever: make sure to use the picture of me and my miniature imaginary accordion for the article
::: Julie_Johnsoned

Google mottos: a history
::: mightygodking

six years in to being a browser engineer on Chrome and I still get random people explaining the internet to me
::: __apf__

Listening to AC/DC
::: fabrizio_sitzia

#quotd [cookie]-> The world is coming to an end
::: raspitux

Programming isn’t about what you know
::: CodeWisdom

2018 v 2060
::: _youhadonejob1

The best teams are comprised of members that can operate in a system
::: RichRogersIoT

Risolto il mistero di quanti utenti attivi siano rimasti ancora su Tumblr
::: SusannaQua

The $25,000,000,000,000 Matrix
::: Abstruse Goose

Proposal: Let’s all agree to ban totally-uncontrollable berserker killer robots
::: RebeccaCrootof

When we break up big things into small pieces we invariably push the complexity to their interaction
::: RichRogersIoT

Ché poi l’obiettivo della maglietta nerd è principalmente
::: bermat

At big companies process becomes a substitute for thinking
::: RichRogersIoT

How I made my Programming Language 10,000x Faster
::: TheMichaelBurge

Police Repeatedly Shoot Tim Cook After Mistaking iPhone For Gun
no, non è possibile: quello è bianco
::: TheOnion

Finally, a chance to edit my paper! Let’s open the folder
::: legogradstudent ::: AcademicsSay

California’s new Mandatory coffee Warning
::: MattsIdeaShop

I have reported them to FBI which is a parent company of FB
::: imonahov

Haven’t seen a UX so bad since Geocities in the 90s
::: hakimrah

I like how Window’s BSOD has been getting more and more non-threatening over the years
::: MashAllPotatoes

dev’essergli presa un po’ la mano con questa sperimentazione di design sempre più nuovi e creativi
rimasta così per ore; poi è tornata lo schifo usuale
::: emenietti

CAPTCHA
::: PWTooStrong

Ok… Quick poll. If you had to pick one
::: strandjs ::: mikko

write a short tribute to 2.6 into the code on the place of all deleted legacy code
::: eumiro

It’s one thing to start a book
::: wallingf

My motto is always, “If you’re not overprepared
::: wallingf

The only way to learn a new programming language
::: CodeWisdom

A non-existent or underpowered type system forces you to program defensively; a powerful type system liberates you to program fearlessly
::: jdegoes

Medium follows DNT, except for the N and the T
::: ketralnis

Eccoli, i robot che arrubbano il lavoro ai candidati premier votati dal popolo
::: carloalberto

A random whatsapp forward
::: binitamshah

Not sure why you think Siri is so behind
::: Shaun_Jensen

Thread: Ask me ANY difficult question, and I will respond to them the same delusional way @facebook’s Mark Zuckerberg would
::: Spacekatgal

Building software isn’t like assembling a car
::: RichRogersIoT

#UltimOra, #Facebook introduce la funzione ‘Visualizzato da Cambridge Analytica’
::: lercionotizie

having productive conversations when I disagree
Julia la ❤️ lovvo ❤️
::: b0rk ::: julielerman

Ideas are easy
::: RichRogersIoT

Tabs and spaces each have their advocates
::: TheMichaelBurge