Haskell – 48 – tipi di dati algebrici ricorsivi- 4

Continuo da qui, copio qui, scrollare fino a “Binary search”.

Ricerca binaria
How do we implement functions corresponding to isElementSorted and insertSorted for tree types in Haskell? Let us start with the insertion function. As a precondition, we require that the input tree is sorted: for each node, all the values in the left subtree are less than the value stored in the node, and all the values in the right subtree are equal or greater than the value stored in the node. As a postcondition, we promise that the resulting tree will be sorted as well.

-- precondition: tree is sorted in increasing order
-- postcondition: return tree is sorted in increasing order
insertTree :: Ord a => a -> BinaryTree a -> BinaryTree a
insertTree x Leaf
  = Node x Leaf Leaf

If the tree is non-empty, we have to check whether to insert the item into the left or the right subtree. If the new item is less than the node value, we have to insert it in the left subtree; otherwise in the right subtree:

insertTree newValue (Node nodeValue leftSubtree rightSubtree)
  | newValue < nodeValue = Node nodeValue (insertTree newValue leftSubtree) rightSubtree
  | otherwise            = Node nodeValue leftSubtree (insertTree newValue rightSubtree)

The isElementTree function is quite similar, as we have to consider the same cases. If a tree is empty, isElementTree should always return False, independent of the value we are looking for:

-- precondition: tree is sorted in increasing order
isElementTree :: Ord a => a -> BinaryTree a -> Bool
isElementTree x Leaf = False

Otherwise, there are three possible cases: (1) the current node value is already the value we are looking for and we are done; (2) we have to search in the left subtree if the value is smaller than the value in the node; or (3) we have to search in the right subtree, otherwise.

isElementTree value (Node nodeValue leftSubtree rightSubtree)
  | value == nodeValue  = True
  | value  <  nodeValue = isElementTree value leftSubtree
  | otherwise           = isElementTree value rightSubtree

After all this work, let’s see if this indeed fixed the problem: is inserting and searching in a binary search tree faster than in a sorted list? As we observed previously, if we can reduce the size of the search space by half in each step —that is, if the number of nodes in each of the two subtrees is roughly the same— we need significantly fewer steps. More formally, log2 n recursive steps for a tree with n nodes. This means, for example, that we can search a tree with about 1000 items in 10 steps — a huge improvement over lists.

Bilanciamento
There is a catch, though: to half the search space in each step, the two subtrees of each node need to contain about the same number of values, or in other words, the tree needs to be balanced. Now, while insertTree ensures that, given a sorted binary tree, the resulting tree will be sorted again, it does not ensure that the result will be balanced.

As an example, let’s consider two trees built by inserting the values from 1 to 7 in different order. Specifically, the following images display the binary trees resulting from evaluation

insertTree 5 $
  insertTree 7 $
    insertTree 1 $
      insertTree 3 $
        insertTree 6 $
          insertTree 2 $
            insertTree 4 Leaf

and

insertTree 7 $
  insertTree 6 $
    insertTree 5 $
      insertTree 4 $
        insertTree 3 $
          insertTree 2 $

This next screencast demonstrates how insertion order affects tree shapes, (di là).

These examples clearly demonstrates that if we are not careful about the order in which we are inserting elements, the resulting binary tree will not just be unbalanced, it might even degenerate into a list. Searching for elements in such a degenerate tree is as inefficient as it is on plain lists. There exist many different approaches to ensuring that a tree is balanced in situations where we cannot control the order of insertions. They all come with different trade offs and discussing them in any detail is beyond the scope of this chapter.

Nuovi tipi
Recall the definition of the String type:

type String = [Char]

String is a type synonym — i.e., the types [Char] and String are the exact same thing as far as the type checker is concerned. We can use them interchangeably; String is just a more readable name. This is what we want, in the case of String, as we would like to be able to use all the standard list operations on String values.

In other situations, we like to introduce a new type name for an already existing type and, at the same time, prevent the original and new type to be used interchangeably. For example, we may want distinct types for various physical units, such as Celsius and Fahrenheit, both of which we represent with Floats. In that case, we certainly don’t want values of Celsius and Fahrenheit to be used interchangeably, even if they are both represented by the same basic type, namely Float. We can achieve this as follows by wrapping the basic type into a data type with only one constructor taking one argument:

data Celsius    = Celsius    Float
data Fahrenheit = Fahrenheit Float

In contrast to using a type declaration, this ensures that Celsius and Fahrenheit are distinct types and using values of one for the other will lead to a type error.

As this is a common situation and because the wrapper data types introduce significant inefficiencies, especially when wrapping elementary types, such as Float, Int, and so forth, Haskell supports newtype declarations for the special case of data types with one data constructor with a single argument.

newtype Celsius    = Celsius    Float
newtype Fahrenheit = Fahrenheit Float

With those definitions, we have

Celsius 0 == Fahrenheit 0 ⇒ *** Type mismatch

🤩

Annunci

Essere semplici

Python è uno dei miei linguaggi preferiti. Recentemente mi è capitato di aggiornare script vecchi, scritti da me e da altri, di parecchi non si conosce l’autore. Ho materiale per un paio di post, oggi comincio con uno elementare ma per me che sono niubbo di una certa importanza.

Mi è successo di trovare, più volte, delle espressioni come queste:

Il risultato è chiaro:

e se ripeto l’istruzione torno al valore precedente

Non so se è corretto ma da noi questo è conosciuto come flip-flop (lo so che è anche un’altra cosa 😋).

Ma –tranne casi particolari– secondo me non si deve usare. Scrivere invece ok = True o ok = False. Il perché è semplice: nel debug (o aggiornamento) non devo ricordarmi il valore corrente per negarlo (ovviamente deve saperlo il programmatore iniziale).

Inoltre c’è il duck typing e Python ne è dentro fino al collo. Una variabile non solo varia (OK, come fanno le variabili ma adesso sono indaffarato con la programmazione funzionale) ma varia anche il tipo. E capitano cose come queste:

Siamo passati in modo trasparente da int a bool.

In certi linguaggi si definisce false come 0 e true come 1, o, –spesso– come non 0. È il nostro caso?

No, non esattamente: c’è identità tra 0 e False e tra 1 e True ma per gli altri valori non si sa.

Non ci limitiamo agli interi

Tra le versioni 2.x e 3.x è cambiata la sintassi per la valutazione dell’ugualianza tra valori. Mentre prima si usava <> per dire diverso adesso si deve scrivere !=

Ma capitano cose impreviste

cioè in questo caso è diverso da entrambi i possibili valori booleani. In questi casi –che non si dovrebbero usare– fare sempre il cast:

Dovrebbe essere possibile anche questo

anche se potrebbero insorgere problemi di arrotondamento.

E si può trafficare anche con le stringhe (ht _s 😁):

Non so se questo post ha una qualche valenza. Ma a me è capitato 😡

🤩

Haskell – 47 – tipi di dati algebrici ricorsivi- 3

Velcro

Continuo da qui, copio qui, scrollare fino a “Binary Trees”.

Alberi binari
If we store a collection of items in a list [a], we can easily insert a new item by making this item the new head of the list using the list constructor (:) :: a -> [a] -> [a].

insert :: a -> [a] -> [a]
insert = (:)

Checking if an item is in the list is also straightforward: we can use the elem function from the Prelude or define it ourselves — in either case, we need the element type a to conform to the type class Eq, though:

isElement :: Eq a => a -> [a] -> Bool
isElement _ []     = False
isElement a (x:xs)
  | a == x         = True
  | otherwise      = isElement a xs

As we can see from this definition, the isElement function has no choice but to potentially look at every single item in the list to determine whether it is the value we are looking for. Depending on the length of the list, this can be rather time consuming. Can we do better?

Liste ordinate
If we had to do such a task in the physical world, we might try to keep our sequence sorted, so we can stop the search as soon as we reach an item which is smaller than the item we are looking for.

-- precondition: list is sorted in increasing order
isElementSorted :: Ord a  => a -> [a] -> Bool
isElementSorted _ []     = False
isElementSorted a (x:xs)
  | a == x               = True
  | a > x                = False
  | otherwise            = isElementSorted a xs

Now that we need greater (>), the Eq a constraint is no longer sufficient and we need to use Ord to ensure the element type a supports a total ordering. Nevertheless, Haskell cannot ensure the informally stated precondition, namely that the argument list is actually sorted. Hence, if we apply elemSorted inadvertently to an unsorted list, we may get an incorrect result:

isElementSorted 3 [1, 2, 5, 3] ⇒ False

Nevertheless, if applied to sorted lists, isElementSorted only has to inspect every single item if the value of the item we are looking for is greater or equal to the last one in the list. This is slightly better than our original definition isElement, but it does not actually solve the problem. In particular, we do not get this improvement for free, as we have to change the implementation of the insert function, to ensure that, if we insert in a sorted list, the resulting list is sorted as well:

-- precondition: list is sorted in increasing order
-- postcondition: return list is sorted in increasing order
insertSorted :: (Eq a, Ord a)  => a -> [a] -> Bool
insertSorted x []     = [x]
insertSorted x (y:ys)
  | x <= y            = x : y : ys
  | otherwise         = y : insertSorted x ys

In contrast to insert, which takes just a single step, no matter how long the list, insertSorted may have to traverse the whole list to find the correct spot for the new element; so, overall, merely using sorted lists is not likely to improve our program.

To see what went wrong, let’s again consider how we would deal with such a task in real life. To search for a particular item in a sorted stack, for example, we definitely wouldn’t start from the first item and proceed, one by one, to the last. Instead, we might split the stack into roughly equal halves. Then, we would check if the item we are looking for is the middle one and, if not is, whether it is bound to be in the first or second half, depending on whether the item we are looking for is smaller or greater than we one in the middle. Based on this check we can discard either the first or second half of the pile and continue our search with the same strategy in the remaining stack. This is significantly faster, in particular for large sequences, as we discard about half of the remaining items in every step, instead of just a single one. This strategy is called binary search.

Alberi binari
Unfortunately, binary search isn’t directly applicable to lists! There is simply no way in which we can directly get to the middle of a list without traversing the first half, element by element.

What is the alternative? What we need to implement binary search is a data structure that lets us get to the middle of a collection of sorted elements in one step; then, we need to be able to do the same with whichever half of the original collection we select after the first comparison. Such a recursive structure, which has more than one sub-structures of the same type is a tree. Our tree has exactly two subtrees, and is therefore a binary tree. Its definition is (apart from the names) quite similar to that of List:

data BinaryTree a
  = Node a (BinaryTree a) (BinaryTree a)
  | Leaf

Or, if you prefer the generalised syntax:

data BinaryTree a where
   Node :: a  -> BinaryTree a -> BinaryTree a -> BinaryTree a
   Leaf ::                                       BinaryTree a

A Leaf corresponds to Nil and Node to Cons, with the difference that Cons only had one sublist, whereas Node has a left and the right subtree.

The following screencast illustrates the construction of binary trees, di là.

🤩

Haskell – 46 – tipi di dati algebrici ricorsivi- 2

Continuo da qui, copio qui, scrollare fino a “Generalised Syntax”.

Sintassi generalizzata
[Previously], we briefly discussed the generalised notation for algebraic data types enabled with the GADTs language pragma. In that generalised notation, Maybe is defined as

data Maybe a where
    Just     :: a -> Maybe a
    Nothing  ::      Maybe a

The data constructor Just can be viewed as a function that takes a value of type a and returns a Maybe a, and Nothing as a constant which returns a Maybe a value of any type a. In other words, the data constructors of a parametric data type are themselves parametric polymorphic functions — i.e., functions whose type signature contain unconstrained type variables, here the a.

Costruttori di tipo ricorsivo
Just like the Maybe type constructor, the list type constructor [] is parametric — i.e., it takes as a type argument the list’s element type. And although lists come with special, builtin syntax (the square bracket notation), we can define a data type that is functionally equivalent to standard Haskell lists. Standard Haskell lists come with two parametric polymorphic data constructors: [] :: [a], which returns an empty list of any type a, and (:) :: a -> [a] -> [a], which adds an element to the front of a list. The new and interesting point about lists is that the type of the second argument of the data constructor (:) is the list type itself — in other words, the definition of lists depends on itself. Hence, we call such types recursive (just as with functions whose definition depends on itself).

The following recursive data type definition corresponds functionally to that of the builtin list type. However, it uses two alphanumeric data constructor, Cons and Nil, instead of the builtin special syntax, [] and (:). (Strictly speaking, user-defined data constructors can be formed from infix symbols, starting with a colon character (:). However, [] is not in the realm of notation that can be used in user-provided definitions.)

data List a
  = Cons a (List a)
  | Nil

or, alternatively, in the generalised syntax

data List a where
  Cons :: a -> List a -> List a
  Nil  ::                List a

Conceptually, our new List type is the same as builtin lists, just without the syntactic sugar of the bracket notation. Hence, we need to write

Cons (Cons (Cons (Const 4 Nil) 3) 2) 1)

instead of the more compact [1, 2, 3, 4]. We can, however, use infix notation as with 1 : 2 : 3 : 4 : [] by enclosing Cons in backquotes:

1 `Cons` (2 `Cons` (3 `Cons` (4 `Cons` Nil)))

(We could even avoid the parentheses by using a suitable infix operator declaration to fix the associativity of Cons.)

So in practice, we will rarely find the need to define lists ourselves (and instead use the syntactically more convenient builtin ones). However, lists as a collection type are limited, and we will see that we can often do better with user-defined recursive data types of a different structure.

🤩

Haskell – 45 – tipi di dati algebrici ricorsivi- 1

Continuo da qui, copio qui.

Nota: siccome sono ancora troppo principiante salto gli esercizi proposti alla fine del capitolo precedente. Ho raccontato delle mie difficoltà qui.

The first chapter on Algebraic Data Types [posts precedenti] discussed the fundamental aspects of algebraic data types. In the following, we go deeper by discussing parameterised and recursive data types. The former are also called generic in other programming languages and the latter enable us to construct arbitrary tree structures.

Tipi di dati parametrizzati
[We have already] discussed the concept of partial functions; that is, functions which only successfully return result values for a subset of their possible argument values — we call this subset the domain of the function. If the function is applied to arguments outside its domain, it raises a runtime error. For example, the index function (!!) :: [a] -> Int -> a only returns a value if the second argument, the index, is greater or equal to zero, and the list has sufficiently many elements. Applying it to other combinations of values will trigger a runtime error. Consider the the following examples, where we assume xs = ['a', 'b', 'c', 'd']:

xs!!2   ⇒   'c'
xs!!4   ⇒   *** Exception: Prelude.!!: index too large
xs!!(-1)   ⇒   *** Exception: Prelude.!!: negative index

If we want to avoid such runtime errors, we need to test whether arguments are admissible before calling a partial function, such as (!!), as in the following example:

showFifthElement :: Show a => [a] -> String
showFifthElement xs
  = if length xs < 5
      then "there is no fifth element in this list"
      else "the fifth element of the list is: " ++ show (xs !! 4)

While that test is simple (even if inefficient) in the above example, that is not always the case. In general, especially if the tests become more involved, it is nicer to turn the partial function (here (!!)) into a total one by wrapping its return type into a new data type that avoids failure by turning it into a special return value:

data MaybeInt
  = Just Int
  | Nothing

We can use this new data type to define a total indexing function on lists of Ints. (Note how infix functions can be defined for custom symbols using the infix notation in the function definition.)

(!+!) :: [Int] -> Int -> MaybeInt
[]      !+! _ = Nothing
(x : _) !+! 0 = Just x
(_ :xs) !+! n = xs !+! (n - 1)

Using this new function, the definition of showFifthElement becomes:

showFifthElement :: [Int] -> String
showFifthElement xs
  = case xs !+! 4 of
      Nothing -> "there is no fifth element in this list"
      Just n  -> "the fifth element of the list is: " ++ show n

The use of Maybe is illustrated in the following screencast [di là].

🤩

Visto nel Web – 315

Lista lunga, con preoccupazione riguardo la Net Neutrality. Se lo fanno i ‘mericani poi c’è il grosso rischio che lo facciano anche da noi. Intanto ecco cosa ho wisto nel Web 😋

Runge phenomena
#:programming, codice, snippet
::: John D. Cook

Musk-Backed ‘Slaughterbots’ Video Will Warn the UN About Killer Microdrones
ma il futuro è sempre diverso da come te l’eri immaginato (imho)
#:innovazioni, futuro #:artificial intelligence
::: Slashdot ::: amasad

In case anyone was wondering, there IS a major academic field devoted to the study of algorithms, data, and technology. Several fields, in fact
#:algoritmi, codice
::: sivavaid

Jargon from the functional programming world in simple terms
#:programmazione funzionale
::: Jose_A_Alonso

Slides for the talk I gave yesterday: So you want to be a wizard
#:programming, codice, snippet
::: b0rk

10-Year-Old Boy Cracks the Face ID On Both Parents’ IPhone X
#:sicurezza, spionaggio, virus
::: Slashdot

L’IoT del futuro esaudisce i desideri degli utenti – BitMat
#:artificial intelligence
::: fulcorno ::: fulcorno ::: IndrainItalia ::: fulcorno

“Who Filters Your News? Why we built gobo.social”
non sicuro che sia la risposta giusta; poi chissà se funziona per l’italiano
#:social media
::: datatheism

Ouch – Intel ends support for legacy BIOS in 2020
#:innovazioni, futuro
::: binitamshah

cmd — Line-oriented Command Processors
#:linguaggi di programmazione
::: PyMOTW-3

Very excited today to open source wsk
A small JavaScript library combined with a recommended architecture for creating a reliable build system. It was built by the Bloomberg Graphics and Data Journalism team as an open-ended and maintainable solution to building projects
#:linguaggi di programmazione
::: mhkeller

Security Problems Are Primarily Just Bugs, Linus Torvalds Says
#:sicurezza, spionaggio, virus
::: Slashdot

The enduring power of print for learning in a digital world
#:media #:scuola, educazione
::: demartin

Spam Is Back
#:spam
::: Slashdot

What I tell all new programmers
#:programming, codice, snippet
::: RichRogersIoT

The Secret to Tech’s Next Big Breakthroughs? Stacking Chips
#:hardware
::: Slashdot

CMUCL is now 37 years old. Evolved into Common Lisp early on. One of the oldest continuously supported Lisp implementations. Public Domain
#:lisp(s)
::: RainerJoswig

Good insights about software engineering, focused on data science
#:programming, codice, snippet
::: gvanrossum

Deep Learning Is Eating Software
#:artificial intelligence
::: Slashdot

Over 400 of the World’s Most Popular Websites Record Your Every Keystroke
#:Web, Internet
::: Slashdot

Modern Media Is a DoS Attack on Your Free Will
#:Web, Internet
::: marcelsalathe

Yup, the Russian propagandists were blogging lies on Medium too
#:sicurezza, spionaggio, virus #:fake news, bufale
::: pnhoward ::: fabiochiusi

‘…the new Facebook will be rebuilt inside the carcass of the old, and they will share blood’
#:protagonisti #:social media
::: tanyalokot

Earlier this month, @izvestia_ru claimed that Fb said it would move data to Russians servers
#:social media #:politica
::: KevinRothrock

Google Collects Android Users’ Locations Even When Location Services Are Disabled
#:sicurezza, spionaggio, virus
::: Slashdot

Informative page for #Haskell noobs I just learned about
#:programmazione funzionale
::: gknauth

Despite evidence that Russian manipulation accounts have returned to Twitter, and that some likely remain, Twitter has not provided Congress with details on any other accounts
#:sicurezza, spionaggio, virus
::: josephfcox

Let me get this straight: we need to regulate FB/Google/Twitter to save democracy, and at the same time to give ISPs the ability to discriminate content as they please to save the market
#:social media
::: fabiochiusi

To Save Net Neutrality, We Must Build Our Own Internet
#:Web, Internet
::: Slashdot

Alexa and @arduino Smart Home Challenge – “We invite you to create a project that envisions the future of smart homes”
#:innovazioni, futuro
::: mbanzi

Do relational databases evolve toward rigidity?
#:programming, codice, snippet
::: Daniel Lemire

New iPhone Exhibit Celebrates the “One Device that Changes Everything”
#:innovazioni, futuro
::: Computer History Museum

Today in Internet history: the first ARPANET link was established between @UCLA & @Stanford
#:storia
::: MIT_CSAIL

I’m really happy to announce that the AT&T 3B2 400 emulator has been merged back into the main SIMH sources
uh! avendo tempo…
#:storia
::: Twylo

Il gigante orientale dell’e-commerce si fa sempre più “fisico”
#:economia
::: PeriodiciValori

Algorithmic trading in Python—an impressive intro tutorial
#:programming, codice, snippet
::: dbader_org

Why Apple’s HomePod Is Three Years Behind Amazon’s Echo
#:hardware
::: Slashdot

Russia To Act Against Google if Sputnik, RT Get Lower Search Rankings
#:Web, Internet
::: Slashdot

In Portugal, with no net neutrality, internet providers are starting to split the net into packages
#:Web, Internet
::: RoKhanna

Replacing x86 firmware with Linux and Go
#:sistemi operativi
::: Donearm

5 approaches to learning Python
#:linguaggi di programmazione
::: lucaciavatta

What journalists need to know about the new net neutrality battle
#:Web, Internet
::: journalismfest

Con “Essere digitali”, il laboratorio di @demartin
#:scuola, educazione
::: riconnessioni

Born in a Van: Happy 40th Birthday to the Internet!
#:storia
::: Computer History Museum

China’s Tencent Breaks Through $500bn Stock Market Capitalisation
#:social media #:economia
::: Slashdot

Let’s play with Regular Expressions #Haskell
#:programmazione funzionale
::: Jose_A_Alonso

My take on #NetNeutrality, without using that term
::: dsearls

BuckleScript 2.1 is out
A JavaScript backend for OCaml focused on smooth integration and clean generated code
#:linguaggi di programmazione
::: bobzhang1988

it’s groups of people coming together to solve problems
#:programming, codice, snippet
::: WeAreHitachi

Tre cattive notizie in fila su Uber, Apple e Google
#:economia
::: _aloisi

Qualsiasi domanda su Haskell è benvenuta sul canale IRC di @Haskell_ITA anche le più difficili
per quando riuscirò a haskellare
#:programmazione funzionale
::: volothamp

What is this if not censorship pushed by American propaganda? If you are so disturbed by RT articles and you are unable to counter-comment it says more about today’s American society than anything else
#:censura
::: libertNation

Finally someone explained monads in a way that is actually possible to understand
uh! parte bene poi… ce l’ha con Haskell?
#:programmazione funzionale
::: PaniczGodek

Here’s Facebook’s forthcoming tool to tell if you followed accounts created by the Kremlin-linked Internet Research Agency
#:sicurezza, spionaggio, virus
::: josephfcox ::: jacknicas

Manisha Agarwal

C-Reduce is great at reducing languages other than C and C++: Racket, Java, Rust, whatever also, it is available as a binary package for most any unix-ish OS
per debuggers estremi
#:linguaggi di programmazione
::: johnregehr

Important thread from the ACLU calling on Facebook to submit to independent auditing
#:social media #:sicurezza, spionaggio, virus
::: JuliaAngwin

Apple Scientists Disclose Self-Driving Car Research
#:artificial intelligence
::: Slashdot

Compile-time format string checks FTW!
#:programming, codice, snippet
::: vzverovich

La neutralità della rete serve per la libertà di tutti
#:Web, Internet
::: WikimediaItalia

You are your tools
#:tools, componenti software
::: Daniel Lemire

Announcing Rust 1.22 (and 1.22.1)
#:linguaggi di programmazione
::: The Rust Programming Language

Don’t worry about how big or established your competitor is. Use their massive size against them
#:innovazioni, futuro
::: RichRogersIoT

.@nature expanding into machine intelligence by launching a new journal dedicated to AI, ML, robotics, etc., including place in society
#:artificial intelligence
::: lrvarshney

How good is currently available speech synthesis? Have a listen to Google WaveNet. And be blown away
#:algoritmi, codice
::: amcafee

Study Finds 43% Drop in Time Spent on Facebook from last year
#:social media
::: PamellaNeely

Why microservices are a security issue
#:programming, codice, snippet
::: lucaciavatta

My Open Culture Studio in @centrumcyfrowe is running a competition for best apps reusing digitised heritage
#:programming, codice, snippet
::: EwaMajdecka

Verified functional algorithms – Andrew W. Appel
#:programmazione funzionale
::: Jose_A_Alonso

Hey software engineers, remember how you were going to resist the coming dystopia? You can do it by refusing to work on this project and shaming any company that cooperates
#:sicurezza, spionaggio, virus
::: evacide

Aula d’informatica di una scuola elementare
#:innovazioni, futuro
::: MattScherbatsky

Dal Politecnico di Torino, l’Internet of Things che riconosce i nostri gusti
#:artificial intelligence
::: PoliTOnews

Mobile phones were a big change for people in rich countries like the US where most had access to landline phones. But they were a really huge change for people in poorer countries like Kenya
#:innovazioni, futuro #:dispositivi mobili
::: MaxCRoser

‘We Are Disappointed’: Tech Companies Speak Up Against the FCC’s Plan To Kill Net Neutrality
::: Slashdot

No ai robot censori di Stato per il web. Governi UE sempre più isolati nella discussione sul #copyright dopo voto di commissione #Europarlamento
#:censura
::: WikimediaItalia

Google’s Eric Schmidt Says People Want Dish-Washing Robots To Clean Up the Kitchen More Than Any Other Kind
yepp me too
#:artificial intelligence
::: Slashdot

An open letter to FCC chairman
#:Web, Internet
::: fabiochiusi

Justin Trudeau Is ‘Very Concerned’ With FCC’s Plan to Roll Back Net Neutrality
#:Web, Internet
::: Slashdot

MonadBaseControl in five minutes
per me per adesso è misterioso, per il futuro
#:programmazione funzionale
::: Jose_A_Alonso

Great post about mass surveillance and the First Amendment
#:sicurezza, spionaggio, virus
::: JameelJaffer

Dependent types in Haskell
#:programmazione funzionale
::: Jose_A_Alonso

Democracy swamped by spambots
#:Web, Internet
::: BartoszMilewski

Why we never thank open source maintainers
#:free open source software
::: mbanzi

TeX Live Cockpit – A new frontend for TeX Live Manager
#:tools, componenti software
::: norbusan

Nuova guida tematica di Claudio Beccari “Come creare un esempio minimo compilabile con LaTeX2ε”
#:manuali, how to
::: guitexorg

EU Lawmakers Back Exports Control on Spying Technology
#:sicurezza, spionaggio, virus
::: Slashdot

Munich council finds €49.3m for Windows 10 embrace
disastro? o ono i politici? o Linux non è per la gente normale?
#:sistemi operativi
::: dcavedon ::: italovignoli

There’s Now a Dark Web Version of Wikipedia
#:sicurezza, spionaggio, virus #:censura
::: Slashdot

Programmable CAD
#:tools, componenti software
::: Numbers and Shapes

Come la propaganda renziana su Facebook è diventata la copia di quella grillina
#:fake news, bufale #:politica
::: VICE

ARM assembler in Raspberry Pi
#:manuali, how to
::: b3h3m0th

“Serious Cryptography” book is out
#:manuali, how to
::: b3h3m0th

code::dive 2017 conference report
#:programming, codice, snippet
::: b3h3m0th

C++ 17 Features
#:linguaggi di programmazione
::: b3h3m0th

67% of organizations plan to use IoT, but just 1.5% of executives have a clear vision of what IoT will do for them
#:innovazioni, futuro
::: RichRogersIoT

Why expert developers make the worst tech leads
#:economia
::: RichRogersIoT

Pornhub Owner May Become the UK’s Gatekeeper of Online Porn
#:sicurezza, spionaggio, virus
::: Slashdot

No boundaries: Exfiltration of personal data by session-replay scripts
#:dati, raccolta
::: random_walker

Ho notato adesso che la schermata di debug in #Laravel 5.5 include un pulsante “Search for help on #StackOverflow”, con il link diretto alla ricerca per l’eccezione segnalata
#:tools, componenti software
::: madbob

First AMD Ryzen Mobile Laptop Tested Shows Strong Zen-Vega Performance
#:hardware
::: Slashdot

Fake news come legittimazione della censura dei “giusti”
#:censura
::: ttan_

E’ un problema di trasparenza, di tracciare la provenienza delle notizie
#:fake news, bufale
::: gianluca_string

In search of the perfect writing font
#:media
::: iA

HyperHaskell: a graphical interpreter for the programming language Haskell
due cose non ancora viste, ma chissà…
#:programmazione funzionale
::: Jose_A_Alonso ::: Jose_A_Alonso

Il direttore del fallimentare @democratica_web spaccia per inchiesta del NYT un pezzo che racconta il lamento dei renziani (e di Renzi) contro le #FakeNews
#:fake news, bufale #:politica
::: mazzettam

Capita solo a me?

Una storiella di cosa mi è capitato ieri pomeriggio. E poi ho continuato a pensarci; mi tornava in mente a tradimento, anche la notte. Per cui racconto tutto anche se non ci faccio una bella figura 😯 ma chissene 🧙‍

Tutto è partito da questo tweet: Finally someone explained monads in a way that is actually possible to understand.

Seguendo il link si finisce su Quora, qui: How would you explain the purpose and benefit of monads to a non-programmer?

Panicz è un tipo tosto, già visto altre volte, è un little [non tanto little] schemer 😁
Il post è lungo e impegnativo. Parte bene anche se –secondo me– prende la cosa un tantino troppo alla lunga, dai siamo tutti programmatori, magari non consapevoli ma sì, yepp.

Inizia con l’esempio del calcolo del fattoriale in pseudo-assembly. Ehi! quando io ho cominciato, in Fortran, si programmava così 👽
Anche l’evoluzione dell’esempio è quasi-Fortran, mi sa che in futuro ne riparlo.
Panicz poi introduce l’astrazione ed ecco Haskell

factorial 0 = 1
factorial n = n * factorial(n - 1)

che possiamo ridurre a

factorial n = fold (*) [1..n]

Però una cosa: Note that the above formulation is ambiguous, because we don’t know the order in which expressions should be reduced. If we interpret the expression as (((a ▽ b) ▽ c) ▽ d), we get a left fold, and if we interpret it as (a ▽ (b ▽ (c ▽ d))), we get a right fold.

Ecco qui mi sono perso. Cerrrto colpa mia, solo mia ma… adesso vi conto.

Non ho resistito e ho lanciato GHCi

OK, come previsto ma con (-) si ha

Verifico, è semplice e poi c’è la definizione lì sopra delle due funzioni… E qui il dramma: il -7 non mi viene.

In questi casi so benissimo che sono io che sto sbagliando, che basterebbe scrivere su carta (come si faceva una volta, come dovrei fare sempre, mi conosco, so di essere pasticcione…) e tutto diventa chiaro, così:

(2 - (3 - (4 - 10)))

e ovviamente

Ma non sono stato così razionale. Ho risolto mentalmente l’equazione, sbagliando di nuovo 👿

Panico 👿
No, non mi sono ricordato che in questi casi devo smettere, andare a farmi un caffè o due passi, ho ben quattro cani che adorano le passeggiate anche se sono in aperta campagna, volendo possono farsele da soli, anche se non è notte e non si deve necessariamente abbaiare.

Insomma, non me lo so spiegare ma ci ho messo parecchio prima di decidermi a operare passo-passo, così

(2 - (3 - (4 - 10))) =
(2 - (3 - (-6))) =
(2 - (3 + 6)) =
(2 - 9) =
-7

OK! E sì le parentesi più esterne non sono necessarie ma l’abitudine –mia, il Lisp.

C’è un ulteriore motivo (recondito direi, se sapessi cosa vuol dire) che mi ha panicato e continua a panicarmi: il tutorial che sto seguendo alla fine di ogni lezione propne esercizi; di solito semplici ma Haskell non sono ancora riuscito a farlo mio, è diverso dagli altri linguaggi. Gli esercizi sono senza soluzione, e chissà se quello che ho scritto è vero. Poi proseguendo di solito si scopre che la soluzione viene data nelle trattazioni successive. Intanto panico 👿

Ma sono uscito fuori tema. Stavo scrivendo delle monadi come le vede Panicz.

Panicz ci racconta delle notazioni algebriche: it may or may not be useful to know that mathematicians call a set with an associative operation a semigroup. […] Of course, mathematicians also came up with a name for semigroups with identity element: they are called monoids. (Moreover, if the each element has its inverse element, then this structure is called a group, and is the subject of study of a vast branch of algebra called Group theory.)

For example, strings with concatenation operation form a monoid, where the empty string is the neutral element. But perhaps more importantly, functions with the operation of function composition form a monoid, where the neutral element is of course the identity function. Sì ho saltato la parte relativa all’elemento neutro.

Having the notion of identity element solves yet another problem. Recall the formulation of fold that I gave above. It did not specify what should the value of a fold over an empty list be. Intuitively, the sum of all the elements of an empty list should be 0, for example. For the same reason, the product of all elements of an empty list should be 1.

However, the idea of folding is not limited to monoid, or not even to the things of the same kind. The variants of fold that are most commonly used in Haskell take an additional argument, the “initial value” e, so that, for example, you can understand foldl ▽ e [a,b,c,d] as ((((e ▽ a) ▽ b) ▽ c) ▽ d) and foldr ▽ e [a,b,c,d] as (a ▽ (b ▽ (c ▽ (d ▽ e)))).

Altra digressione qui su version control, poi si passa al lambda calculus, salto che c’è spiegato bene di là. Mica finisce qui, ci sono le callbacks e la pyramid of doom.

E poi:

Monads, finally
So far we have seen that we can usually avoid the pyramid of doom rather easily by introducing new syntactic forms to our language. However, for some reason many programmers do not like to use languages whose syntax is based on s-expressions and prefer other syntaxes that correspond better to their whims. Since these syntaxes make the introduction of new syntactic forms to the language really difficult, they come up with other means to avoid the pyramid of doom.

They suggest that it is a good idea to have a single special form that is able to convert nesting into sequencing, that is implicitly parameterized with some sort of composition operator (this special form is called “do-notation” in Haskell and “for-comprehension” in Scala). The implicit parametrization occurs with the help from the type system (for example, in Haskell it makes use of the mechanism called type classes).

Salto i dettagli, e arrivo al dunque. [T]he developers of Haskell decided that its sequencing operator should be parameterized not only with the composition operator (which is written as >>= and pronounced “bind” in Haskell), but there should also be a “unit” operator that does nothing interesting — or to be more precise, it does nothing in some particular sense (it is called return in Haskell, probably to confuse programmers with background in imperative programming).

Arguably, there are some “monadic laws” that ought to be satisfied by these operators. […]

These laws may remind you the definition of monoids. This should explain at least some bit of the popular phrase “monads are just monoids in the category of endofunctors, what’s the problem?”.

The problem is that neither the notion of category, nor the notion of an endofunctor gives any clues whatsoever with regard to sequencing. […] Salto polemica su IO. E:

TL; DR they allow to replace nesting with sequencing in languages that have a poor support for macros but offer sufficiently elaborate type systems. And they probably allow some programmers to look smart. The name “monad” is terrible, because it focuses on some irrelevant (and unnecessary) details, giving no clue of the purpose whatsoever (truly, the name “sequencing” would be way better).

Insomma Panicz è chiaro ma forse troppo polemico. E, per quanto mi riguarda, mi conferma che le mie difficoltà con Haskell non sono solo mie. Ma insisto, quando il gioco si fa duro… (inizio-cit.) 😉

🤩

Haskell – 44 – tipi di dati algebrici – 11

Continuo da qui, copio qui, scrollare fino a “Record Puns and Wildcards”.

Record puns e caratteri jolly
Come tradurre “record pun”? Nope, non si deve tradurre, come si vedrà subito 😊

We already saw that the record notation permits some freedom in how to decompose records. For instance, we had the example

greenComponent :: Colour -> Int
greenComponent Color{greenC = green} = green

where we bind the value of the record field greenC to the local variable green. We also saw that we can use projection functions instead:

greenComponent :: Colour -> Int
greenComponent colour = greenC colour

Even more compact notation is enabled by a language extension known as record punning, which we can use if we put the pragma

{-# LANGUAGE NamedFieldPuns #-}

at the top of a module or playground. Punning introduces a shorthand for binding record fields to local variables having the same name as the record field. For example,

greenComponent :: Colour -> Int
greenComponent Color{greenC} = greenC -- with punning

is the same as

greenComponent :: Colour -> Int
greenComponent Color{greenC = greenC} = greenC -- without punning

We can also use punning in the construction of records, as in

red = Colour{redC, opacityC, blueC, greenC}
  where
    redC     = 255
    opacityC = 255
    blueC    = 0
    greenC   = 0

Finally, record wildcards, enabled by

{-# LANGUAGE RecordWildCards #-}

take this idea one step further. Instead of enumerating the field names, we can use ellipsis to enable punning for all field names that are not explicitly mentioned. This enables us to write the previous example as

red = Colour{..}
  where
    redC     = 255
    opacityC = 255
    blueC    = 0
    greenC   = 0

and the projection of the green component as

greenComponent :: Colour -> Int
greenComponent Color{..} = greenC -- with wildcard punning

By explicitly mentioning some names, we can, for example, use pattern matching on selected fields, as in this example of a function that returns the opacity of any colour with a fully saturated green channel:

brightGreenOpacity :: Colour -> Int
brightGreenOpacity Color{greenC = 255, ..} = opacityC
brightGreenOpacity _ = error "green not saturated"

Ci devo pensare un po’ su 😯

🤩

Haskell – 43 – tipi di dati algebrici – 10

Continuo da qui, copio qui, scrollare fino a “Data Constructors Versus Functions”.

Costruttori di dati contro funzioni
Data constructors and functions are somewhat similar. Both are applied to arguments, and then, produce a new entity. In fact, both share the same types. For example, we earlier discussed the type of Circle:

Circle :: Point -> Float -> Colour -> LineStyle -> FillStyle -> PictureObject

Hence, we may regard data constructors as a special kind of function, a function that wraps its arguments up, such that they can be unwrapped again by pattern matching. This is in contrast to other functions, where we cannot recover the arguments after the function has been applied. For example, if we know that the application of the function (+) resulted in the Int value 10, we can’t undo this application and determine the arguments. Hence, data constructors are sometimes called free or uninterpreted functions — they merely store, but do not process their arguments.

Moreover, as data type definitions consist of a fixed number of data constructors, we (and the compiler) can infer from the type of an expression a set of patterns that will exhaustively cover all possible values that the expression may evaluate to. In fact, the Haskell system uses that information to generate a warning where patterns are not exhaustive, as this often constitutes an oversight that likely leads to incorrect program behaviour. For example, in the case of a PictureObject, we know the only way to produce a value of this type is as the result of the application of either Path, Circle, Ellipse, or Polygon. We can always determine which one it was, and what the arguments were, either by pattern matching in a function equation or by using a case expression:

showComponents :: PictureObject -> String
showComponents pic
  = case pic of
      Path points colour lineStyle
        -> "The value is the result of the application of `Path` to " ++
           show points ++
           " and " ++
           show colour ++
           " and " ++
           show linestyle
      Circle ...

As data constructors are just a special form of function, we can also partially apply data constructors: the function zeroX is defined in terms of a partial application of the Point constructor, which has type Float -> Float -> Point, to only the first argument:

zeroX :: Float -> Point
zeroX = Point 0

Applying zeroX to 5 yields, as expected, Point 0 5. Pattern matching can only be used on a data constructor once it has been applied to all its arguments — that is, we cannot use pattern matching on zeroX to extract the 0 without first applying zeroX to a second argument.

Sintassi generalizzata per dati algebrici
The similarity between data constructors and functions is the foundation for an alternative syntax for declaring algebraic data types, often called the generalised syntax for algebraic data types, as it enables declarations that cannot be expressed with the standard syntax. We defer discussing the new capabilities enabled by the generalised syntax to a subsequent chapter of this tutorial, as it is an extensive topic in itself. However, we outline the basic notation here, as it nicely illustrates the notion of data constructors as functions. Specifically, the generalised syntax simply consists out of declaring data constructors by way of their function signature and is identified by using the where keyword instead of an equality symbol (=) after the declaration head. For example,

data Point = Point Float Float

becomes

data Point where
  Point :: Float -> Float -> Point

Similarly, the initial version of the PictureObject data type can be defined as follows with the generalised syntax:

data PictureObject where
  Path    :: [Point] ->                            Colour -> LineStyle              -> PictureObject
  Circle  :: Point   -> Float ->                   Colour -> LineStyle -> FillStyle -> PictureObject
  Ellipse :: Point   -> Float -> Float -> Float -> Colour -> LineStyle -> FillStyle -> PictureObject
  Polygon :: [Point] ->                            Colour -> LineStyle -> FillStyle -> PictureObject

To declare records with the generalised syntax, we put the record fields in braces, much like in the standard syntax. For example, we have

data PictureObject where
  Path :: { pointsPO    :: [Point]
          , colourPO    :: Colour
          , lineStylePO :: LineStyle
          } -> PictureObject
  ...

The generalised syntax for algebraic data types (also known as GADT syntax) is available as an extension to the standard Haskell language. To use that extension, we need to put the following language pragma at the top of the Haskell module or playground, where we want to use it:

{-# LANGUAGE GADTSyntax #-}

🤩

cit. & loll – 71

Arriva –lo so, in ritardo come il treno ma c’è– eccolo 😯

We are well beyond peak “Semantic Web”
::: lemire

For attending a conference I will give you an indulgence to not read Haskell Book or SICP
::: volothamp

The object-oriented version of spaghetti code
::: CodeWisdom

There are no stupid questions
::: SamKallis

Holy fuck, @BostonDynamics
::: TomNomNom

How to build great software
::: RichRogersIoT

If you give me six lines of C written by the hand of the most honest of men
::: fakalin

We’re happy to be part of Quad9
chissà cos’è (sono niubbo ci sa)
::: mikko

The best developers are constantly trying new languages
::: RichRogersIoT

Computers are good at following instructions
::: CodeWisdom

If someone mentions “quantum fields” in any context related to mind and consciousness
::: Plinz

50% of the computer programming is trial and error
::: CodeWisdom

Software reuse is more like an organ transplant
::: RichRogersIoT

Software and technology advances have direct real world implications
::: _mwc

Damn it, @GitHub’s merging is blocked!
::: pascalpixel

When things get complicated
::: RichRogersIoT

So, Spain just made it illegal to RT things
::: matalaz

Mai discutere con gli sconosciuti in rete
::: a_smeriglia

I just realized that Word is like C and Postscript, a portable output format
::: ehud

Digitale = il problema è accettare che siamo in un’epoca nuova. Abbiamo guadagnato enorme spazio di libertà individuale e come giornalisti dobbiamo avere interesse a difenderlo
::: dontyna

New company t-shirt
::: amasad

Bisognerebbe realizzare corsi su come fingere di non sapere usare un computer o uno smartphone
::: floo1989

gif: pronounced
::: jakevdp

Genetic Engineering
::: Savage Chickens

Implicit arguments are good
::: mietek

I went to my local Starbucks this morning and there was this guy
::: bernabephoto ::: RanfordStealth

Arguing for C over C++ is like arguing for a small government
::: YossiKreinin

Best programming habit to develop
::: andrestaltz

Integers are literally the worst
::: djspiewak

Bob Maloney

Linus’ rants are a high form of entertainment
::: Donearm

The opposite of #KISS (Keep It Simple Stupid)
::: rhundhausen

Imagine programming without fear that functions return null, throw exceptions, or return different outputs for the same input
::: jdegoes

What’s wrong with perl?
::: CodeWisdom

Ideas are easy
::: RichRogersIoT

#cyberwar
::: fpietrosanti

The greatest trick the devil ever pulled
::: martintrojer

I’m trying to get this whole set for my 3B2 work
::: Twylo

Three signs your library is developer-friendly
::: jdegoes

Make everything as simple as possible
::: RichRogersIoT

Learning to code makes kids feel
::: CodeWisdom

This wonderful lady made my day!
::: marcelsalathe

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

Machine Learning
::: pickover