Archivi del mese: aprile 2018

Haskell – 183 – monadi – 4

Emanuele Balboni

Continuo da qui, copio qui.

Una monade simple-state
One of the simplest monads that we can craft is a state-passing monad. In Haskell, all state information usually must be passed to functions explicitly as arguments. Using monads, we can effectively hide some state information.

Suppose we have a function f of type a -> b, and we need to add state to this function. In general, if state is of type state, we can encode it by changing the type of f to a -> state -> (state, b). That is, the new version of f takes the original parameter of type a and a new state parameter. And, in addition to returning the value of type b, it also returns an updated state, encoded in a tuple.

For instance, suppose we have a binary tree defined as:

data Tree a
  = Leaf a
  | Branch (Tree a) (Tree a)

Now, we can write a simple map function to apply some function to each value in the leaves:

mapTree :: (a -> b) -> Tree a -> Tree b
mapTree f (Leaf a) = Leaf (f a)
mapTree f (Branch lhs rhs) =
  Branch (mapTree f lhs) (mapTree f rhs)

This works fine until we need to write a function that numbers the leaves left to right. In a sense, we need to add state, which keeps track of how many leaves we’ve numbered so far, to the mapTree function. We can augment the function to something like:

mapTreeState :: (a -> state -> (state, b)) ->
                Tree a -> state -> (state, Tree b)
mapTreeState f (Leaf a) state =
  let (state', b) = f a state
  in  (state', Leaf b)
mapTreeState f (Branch lhs rhs) state =
  let (state' , lhs') = mapTreeState f lhs state
      (state'', rhs') = mapTreeState f rhs state'
  in  (state'', Branch lhs' rhs')

This is beginning to get a bit unwieldy, and the type signature is getting harder and harder to understand. What we want to do is abstract away the state passing part. That is, the differences between mapTree and mapTreeState are: (1) the augmented f type, (2) we replaced the type -> Tree b with -> state -> (state, Tree b). Notice that both types changed in exactly the same way. We can abstract this away with a type synonym declaration:

type State st a = st -> (st, a)

To go along with this type, we write two functions:

returnState :: a -> State st a
returnState a = \st -> (st, a)

bindState :: State st a -> (a -> State st b) ->
             State st b
bindState m k = \st ->
  let (st', a) = m st
      m'       = k a
  in  m' st'

Let’s examine each of these in turn. The first function, returnState, takes a value of type a and creates something of type State st a. If we think of the st as the state, and the value of type a as the value, then this is a function that doesn’t change the state and returns the value a.

The bindState function looks distinctly like the interior let declarations in mapTreeState. It takes two arguments. The first argument is an action that returns something of type a with state st. The second is a function that takes this a and produces something of type b also with the same state. The result of bindState is essentially the result of transforming the a into a b.

The definition of bindState takes an initial state, st. It first applies this to the State st a argument called m. This gives back a new state st' and a value a. It then lets the function k act on a, producing something of type State st b, called m'. We finally run m' with the new state st'.

We write a new function, mapTreeStateM and give it the type:

mapTreeStateM :: (a -> State st b) -> Tree a -> State st (Tree b)

Using these “plumbing” functions (returnState and bindState) we can write this function without ever having to explicitly talk about the state:

mapTreeStateM f (Leaf a) =
  f a `bindState` \b ->
  returnState (Leaf b)
mapTreeStateM f (Branch lhs rhs) =
  mapTreeStateM f lhs `bindState` \lhs' ->
  mapTreeStateM f rhs `bindState` \rhs' ->
  returnState (Branch lhs' rhs')

In the Leaf case, we apply f to a and then bind the result to a function that takes the result and returns a Leaf with the new value.

In the Branch case, we recurse on the left-hand-side, binding the result to a function that recurses on the right-hand-side, binding that to a simple function that returns the newly created Branch.

As you have probably guessed by this point, State st is a monad, returnState is analogous to the overloaded return method, and bindState is analogous to the overloaded >>= method. In fact, we can verify that State st a obeys the monad laws:

Law 1 states: return a >>= f ≡ f a. Let’s calculate on the left hand side, substituting our names:

     returnState a `bindState` f
==>
     \st -> let (st', a) = (returnState a) st
                m'       = f a
            in  m' st'
==>
     \st -> let (st', a) = (\st -> (st, a)) st
            in  (f a) st'
==>
     \st -> let (st', a) = (st, a)
            in  (f a) st'
==>
     \st -> (f a) st
==>
     f a

In the first step, we simply substitute the definition of bindState. In the second step, we simplify the last two lines and substitute the definition of returnState. In the third step, we apply st to the lambda function. In the fourth step, we rename st' to st and remove the let. In the last step, we eta reduce.

Moving on to Law 2, we need to show that f >>= return ≡ f. This is shown as follows:

     f `bindState` returnState
==>
     \st -> let (st', a) = f st
            in  (returnState a) st'
==>
     \st -> let (st', a) = f st
            in  (\st -> (st, a)) st'
==>
     \st -> let (st', a) = f st
            in  (st', a)
==>
     \st -> f st
==>
     f

Finally, we need to show that State obeys the third law: f >>= (\x -> g x >>= h) ≡ (f >>= g) >>= h. This is much more involved to show, so we will only sketch the proof here. Notice that we can write the left-hand-side as:

     \st -> let (st', a) = f st
            in  (\x -> g x `bindState` h) a st'
==>
     \st -> let (st', a) = f st
            in  (g a `bindState` h) st'
==>
     \st -> let (st', a) = f st
            in  (\st' -> let (st'', b) = g a
                         in  h b st'') st'
==>
     \st -> let (st' , a) = f st
                (st'', b) = g a st'
                (st''',c) = h b st''
            in  (st''',c)

The interesting thing to note here is that we have both action applications on the same let level. Since let is associative, this means that we can put whichever bracketing we prefer and the results will not change. Of course, this is an informal, “hand waving” argument and it would take us a few more derivations to actually prove, but this gives the general idea.

Now that we know that State st is actually a monad, we’d like to make it an instance of the Monad class. Unfortunately, the straightforward way of doing this doesn’t work. We can’t write:

instance Monad (State st) where { ... }

This is because you cannot make instances out of non-fully-applied type synonyms. Instead, what we need to do instead is convert the type synonym into a newtype, as:

newtype State st a = State (st -> (st, a))

Unfortunately, this means that we need to do some packing and unpacking of the State constructor in the Monad instance declaration, but it’s not terribly difficult:

instance Monad (State state) where
  return a = State (\state -> (state, a))
  State run >>= action = State run'
    where run' st =
              let (st', a)    = run st
                  State run'' = action a
              in  run'' st'

Now, we can write our mapTreeM function as:

mapTreeM :: (a -> State state b) -> Tree a ->
            State state (Tree b)
mapTreeM f (Leaf a) = do
  b <- f a
  return (Leaf b)
mapTreeM f (Branch lhs rhs) = do
  lhs' <- mapTreeM f lhs
  rhs' <- mapTreeM f rhs
  return (Branch lhs' rhs')

which is significantly cleaner than before. In fact, if we remove the type signature, we get the more general type:

mapTreeM :: Monad m => (a -> m b) -> Tree a ->
            m (Tree b)

Now, the nice thing about encapsulating the stateful aspect of the computation like this is that we can provide functions to get and change the current state. These look like:

getState :: State state state
getState = State (\state -> (state, state))

putState :: state -> State state ()
putState new = State (\_ -> (new, ()))

Here, getState is a monadic operation that takes the current state, passes it through unchanged, and then returns it as the value. The putState function takes a new state and produces an action that ignores the current state and inserts the new one.

Now, we can write our numberTree function as:

numberTree :: Tree a -> State Int (Tree (a, Int))
numberTree tree = mapTreeM number tree
  where number v = do
          cur <- getState
          putState (cur+1)
          return (v,cur)

Finally, we need to be able to run the action by providing an initial state:

runStateM :: State state a -> state -> a
runStateM (State f) st = snd (f st)

Now, we can provide an example Tree:

testTree =
  Branch
    (Branch
      (Leaf 'a')
      (Branch
        (Leaf 'b')
        (Leaf 'c')))
    (Branch
      (Leaf 'd')
      (Leaf 'e'))

and number it:

State> runStateM (numberTree testTree) 1
Branch (Branch (Leaf ('a',1)) (Branch (Leaf ('b',2))
       (Leaf ('c',3)))) (Branch (Leaf ('d',4))
       (Leaf ('e',5)))

This may seem like a large amount of work to do something simple. However, note the new power of mapTreeM. We can also print out the leaves of the tree in a left-to-right fashion as:

State> mapTreeM print testTree
'a'
'b'
'c'
'd'
'e'

Nota: sì si potrebbe caricare tutto in GHCi ma sono lazy 😯

This crucially relies on the fact that mapTreeM has the more general type involving arbitrary monads — not just the state monad. Furthermore, we can write an action that will make each leaf value equal to its old value as well as all the values preceding:

fluffLeaves tree = mapTreeM fluff tree
  where fluff v = do
          cur <- getState
          putState (v:cur)
          return (v:cur)

and can see it in action:

State> runStateM (fluffLeaves testTree) []
Branch (Branch (Leaf "a") (Branch (Leaf "ba")
       (Leaf "cba"))) (Branch (Leaf "dcba")
       (Leaf "edcba"))

In fact, you don’t even need to write your own monad instance and datatype. All this is built in to the Control.Monad.State module. There, our runStateM is called evalState; our getState is called get; and our putState is called put.

This module also contains a state transformer monad, which we will discuss in the section on Transformer [prossimamente].

👽

Haskell – 182 – monadi – 3

Continuo da qui, copio qui.

Definizioni
There are three rules that all monads must obey called the “Monad Laws” (and it is up to you to ensure that your monads obey these rules):

  1. return a >>= f ≡ f a
  2. f >>= return ≡ f
  3. f >>= (\x -> g x >>= h) ≡ (f >>= g) >>= h

Let’s look at each of these individually:

legge 1
This states that return a >>= f ≡ f a. Suppose we think about monads as computations. This means that if we create a trivial computation that simply returns the value a regardless of anything else (this is the return a part); and then bind it together with some other computation f, then this is equivalent to simply performing the computation f on a directly.

For example, suppose f is the function putStrLn and a is the string “Hello World.” This rule states that binding a computation whose result is “Hello World” to putStrLn is the same as simply printing it to the screen. This seems to make sense.

In do notation, this law states that the following two programs are equivalent:

law1a = do
  x <- return a
  f x

law1b = do
  f a

legge 2
The second monad law states that f >>= return ≡ f for some computation f. In other words, the law states that if we perform the computation f and then pass the result on to the trivial return function, then all we have done is to perform the computation.

That this law must hold should be obvious. To see this, think of f as getLine (reads a string from the keyboard). This law states that reading a string and then returning the value read is exactly the same as just reading the string.

In do notation, the law states that the following two programs are equivalent:

law2a = do
  x <- f
  return x

law2b = do
  f

legge 3
This states that f >>= (\x -> g x >>= h) ≡ (f >>= g) >>= h. At first glance, this law is not as easy to grasp as the other two. It is essentially an associativity law for monads.

Note: Outside the world of monads, a function . is associative if (f . g) . h = f . (g . h). For instance, + and * are associative, since bracketing on these functions doesn’t make a difference. On the other hand, - and / are not associative since, for example, 5 − (3 − 1) ≠ (5 − 3) − 1.

If we throw away the messiness with the lambdas, we see that this law states: f >>= (g >>= h) ≡ (f >>= g) >>= h. The intuition behind this law is that when we string together actions, it doesn’t matter how we group them.

For a concrete example, take f to be getLine. Take g to be an action which takes a value as input, prints it to the screen, reads another string via getLine, and then returns that newly read string. Take h to be putStrLn.

Let’s consider what (\x -> g x >>= h) does. It takes a value called x, and runs g on it, feeding the results into h. In this instance, this means that it’s going to take a value, print it, read another value and then print that. Thus, the entire left hand side of the law first reads a string and then does what we’ve just described.

On the other hand, consider (f >>= g). This action reads a string from the keyboard, prints it, and then reads another string, returning that newly read string as a result. When we bind this with h as on the right hand side of the law, we get an action that does the action described by (f >>= g), and then prints the results.

Clearly, these two actions are the same.

While this explanation is quite complicated, and the text of the law is also quite complicated, the actual meaning is simple: if we have three actions, and we compose them in the same order, it doesn’t matter where we put the parentheses. The rest is just notation.

In do notation, the law says that the following two programs are equivalent:

law3a = do
  x <- f
  do y <- g x
     h y

law3b = do
  y <- do x <- f
          g x
  h y

👽

Visto nel Web – 338

Ecco cosa ho wisto nel Web. Presto che devo aggiornare ‘buntu 😋

Telegram alle strette, rivela il rischio di avere dispositivi chiusi come gli iPhone
#:censura
::: hronir

demoshell 0.2.0
#:applicazioni, programmi
::: doughellmann

Former Reddit Executive Sees ‘No Hope’ For Reddit
#:social media
::: Slashdot

This article debunks the US Supreme Court’s magical thinking about the Internet. The Internet’s expressive opportunities are not available to all on equal terms
#:Web, Internet
::: FrankPasquale

Racket tip: Syntax remembers where it came from, so macros can tell whether a variable is the original or a shadowing fake
#:language Racket
::: TheMichaelBurge

Micro-targeting, profilazioni, algoritmi: il vero problema etico è l’uso da parte della politica dei dati dei cittadini
#:privacy, sicurezza, spionaggio, virus
::: valigiablu

Jeremy Hunt threatens social media with new child-protection laws
#:privacy, sicurezza, spionaggio, virus
::: fabiochiusi

Jack Ma’s (#CEO #Alibaba ) Original Sales Pitch in 1999 in his appartment…
#:protagonisti
::: jblefevre60

Silicon Valley Investors Wants to Fund a ‘Good For Society’ Facebook Replacement
#:social media
::: Slashdot

Rilasciato #DraftSight 2018 SP2
#:applicazioni, programmi
::: Marcooo83

Science and Technology links (April 22nd, 2018)
#:novità
::: lemire

Understanding surprising JS syntax by visualising the parse tree
#:linguaggi di programmazione
::: _wilfredh

Susan Kare, the most important designer you’ve never heard of. She created the smiling Mc, the trash can, the font suitcase, the dreaded bomb symbol & so many others
#:storia
::: DerfBackderf ::: DerfBackderf

25 years ago today the first major web browser was released: Mosaic 1.0
#:storia
::: MIT_CSAIL

Raspberry Pi: Kali Linux
#:sistemi operativi #:hardware
::: xKaliSec

Enough with the intrusive updates!
#:sistemi operativi
::: lemire

Programming in #Haskell is hard. Not necessarily because Haskell is a hard language, but because programming is hard and Haskell, more than most other languages, requires one to line things up correctly before running the program. That is a good thing
#:programmazione funzionale
::: haroldcarr

Who Has More of Your Personal Data Than Facebook? Try Google
#:privacy, sicurezza, spionaggio, virus
::: slashdot

La versione di Kogan
#:privacy, sicurezza, spionaggio, virus
::: fabiochiusi

Breach detection with Linux filesystem forensics
#:programming, codice, snippet
::: cialunet

Want to see what industrial espionage looks like these days?
#:privacy, sicurezza, spionaggio, virus
::: profmetcalf

The big tech companies exacerbate problems — from monopoly power to the need for a new tax and education system to declining faith in liberal democracy — that are not just technical. They are existential
#:ditte
::: FrankPasquale

Z3 is cool and floating point is scary
compilers come non ti aspetti
#:programming, codice, snippet
::: andreasfrom

Dobbiamo smettere di vivere il mondo dei social come qualcosa di “sostitutivo” e dobbiamo vederlo come qualcosa di aggiuntivo
#:social media
::: RudyBandiera

Hacking a Satellite is Surprisingly Easy
#:privacy, sicurezza, spionaggio, virus
::: Slashdot

Programming in the debugger: willcrichton.net. Discusses how notebooks enable incremental program writing, and contrasts with REPLs. Makes some interesting points regarding persistence, although resumable exceptions have similar upsides too
#:programming, codice, snippet
::: _wilfredh

EU Opens Competition Probe Into Apple’s Bid For Music App Shazam
#:ditte
::: Slashdot

Learning tech design matters! Check out the latest fab publication from my colleague @sayamindu and my advisor @makoshark about the impact of adding more powerful data structures into the @Scratch programming environment for kids
#:linguaggi di programmazione
::: kayleachampion

I’m fascinated by the idea of language-oriented programming. Would you like to learn more about it with me?
#:linguaggi di programmazione
::: alamajesse

lol ok facebook
#:privacy, sicurezza, spionaggio, virus
::: sfiegerman

The only reasons to stay with the iPhone right now have nothing to do with the iPhone
perplutante, assay
#:dispositivi mobili
::: Gianlucadfiore

Compilers are known for doing all sorts of cool optimizations. What about your CPUs itself?
#:programming, codice, snippet
::: dendibakh

Google Accused of Showing ‘Total Contempt’ for Android Users’ Privacy
#:privacy, sicurezza, spionaggio, virus
::: Slashdot

Arxiv is huge and I find it hard to find things relevant to my interests. Playing with https://scirate.com/ seems like a good solution: you can follow sections that interest you, and ‘scite’ (basically ‘like’) papers
#:media
::: _wilfredh

Facebook Sued Over Fake Ads
#:ad, pubblicità
::: Slashdot

Wow! Almost half the reviews are fake, according to this report. “How merchants use Facebook to flood Amazon with fake reviews”
#:caos informativo, fake news, bufale
::: om

US Government Weighing Sanctions Against Kaspersky Lab
#:privacy, sicurezza, spionaggio, virus
::: Slashdot

“There’s good legislation that failed to gain traction in the past that is worth revisiting now,” but groups funded by tech firms are not interested in advancing them
#:privacy, sicurezza, spionaggio, virus
::: FrankPasquale

A gentle introduction to FreeDOS
#:sistemi operativi
::: cialunet

An introduction to the GNU Core Utilities
#:tip, suggerimenti
::: cialunet

Il paradosso della privacy, e quanto siamo disposti a pagare per averla
#:privacy, sicurezza, spionaggio, virus
::: sole24ore

“I Just Google It”. In a new article, @BenjaminToff and I identify three complementary folk theories – “news finds me,” “the information is out there,” and “I don’t know what to believe” – that people draw on as they navigate their information environment
#:privacy, sicurezza, spionaggio, virus
::: rasmus_kleis

Do something vague and dangerous about this horribly vague, dangerous and discredited notion or get regulated – surely that sounds as a sensible way to get things done and digital rights respected, right?
#:caos informativo, fake news, bufale
::: fabiochiusi

There’s a big difference between having skills – knowing how to use the internet – and having understanding – knowing the implications of using the internet
@doteveryoneuk sarebbe da followare ma posta troppo; confido in @fabiochiusi, lui lo segue
#:Web, Internet
::: CassieRobinson

A beautiful circle: Company gets ransomwared. Hires IT company to fix it. Unlocks system in record time. FBI figures out the IT company just paid the bitcoin ransom
#:frodi
::: SeamusHughes

This is a super solid article about how to idiomatically handle errors in @rustlang
#:linguaggi di programmazione
::: klnusbaum

A good overview of the history of parsing
mooolto informativo (almeno per me che sono di una gnuransa encyclopedica) 😐
#:storia
::: etorreborre

Interesting new explainer by Facebook of how they enforce their community standards and their appeal system based on principles of safety, voice, and equity with a mixture of AI and humans, including experts: ‘our enforcement isn’t perfect
#:ditte
::: CharlieBeckett

Netflix, Amazon, and Major Studios Try To Shut Down $20-Per-Month TV Service
#:Web, Internet
::: Slashdot

We and 55 other organizations (inc. @EFF @article19org @creativecommons @edri ) sent a letter to @AxelVossMdEP trying again to present the obvious and well documented arguments against the introduction of a new right for #press #publishers
#:copyright e brevetti
::: communia_eu

“For you to break a policy it has to exist and really be their policy,” Kogan said. “But the reality is that Facebook’s policy is unlikely to be their policy”
#:privacy, sicurezza, spionaggio, virus
::: fabiochiusi

ve la ricordate la #FakeNews sulle #sciechimiche? ecco come è andata a finire
un caso finito bene ma il mondo ne è pieno, anche sulla carta
#:caos informativo, fake news, bufale
::: sbencivu

Facebook, Google and Uber are some of the companies that submit to privacy checkups as a result of settlements w/the feds. The problem? They choose their own watchdogs, and they tend to get good grades despite troubles like Cambridge Analytica
#:privacy, sicurezza, spionaggio, virus
::: TonyRomm

Atlanta Projected To Spend At Least $2.6 Million on Ransomware Recovery
#:privacy, sicurezza, spionaggio, virus
::: Slashdot

Come si stanno adeguando al GDPR Google e Facebook? Quali le criticità?
#:privacy, sicurezza, spionaggio, virus
::: AlessLongo

Announcing npm@6
#:linguaggi di programmazione
::: daw985

Jeff Bezos says he “expects to be scrutinized” by regulators
#:privacy, sicurezza, spionaggio, virus #:ditte
::: business

Facebook Has Hosted Stolen Identities and Social Security Numbers for Years
#:privacy, sicurezza, spionaggio, virus
::: slashdot

“Delta Pointers: Buffer Overflow Checks Without the Checks”
#:programming, codice, snippet
::: johnregehr

Patent ‘Death Squad’ System Upheld by US Supreme Court
#:copyright e brevetti
::: Slashdot

Suspicious Event Hijacks Amazon Traffic For 2 hours, Steals Cryptocurrency
#:privacy, sicurezza, spionaggio, virus
::: Slashdot

Seven Habits of Highly Effective Programmers
#:programming, codice, snippet
::: RichRogersIoT

Instagram Launches ‘Data Download’ Tool To Let You Leave
#:Web, Internet
::: Slashdot

SEC Issues $35 Million Fine Over Yahoo Failing To Disclose Data Breach
#:privacy, sicurezza, spionaggio, virus
::: Slashdot

WhatsApp Raises Minimum Age In Europe To 16 Ahead of Data Law Change
#:privacy, sicurezza, spionaggio, virus
::: Slashdot

Excellent article on language-oriented programming (LOP) in @racketlang. #Guix benefits from a form of LOP through @guilelang
#:language Racket #:linguaggi di programmazione
::: GuixHpc

Spotify versione gratuita: le grandi novità disponibili da oggi
#:Web, Internet
::: Genjuro75

169 scholars of whom 100 are full professors working in the fields of intellectual property, internet law, human rights law and journalism studies at universities all over Europe signed this letter to oppose the proposed press publishers’ right
#:copyright e brevetti
::: communia_eu

Even if we regulate Amazon, break up Google, & #DeleteFacebook, it is “hard to imagine a near future without very large-scale social and economic exchange facilitated by digital platforms. The social & the profit-driven are now alloyed”
#:privacy, sicurezza, spionaggio, virus
::: FrankPasquale

Twitter è in attivo per il secondo trimestre consecutivo
#:social media
::: emenietti

Maximilian Teodorescu

Two hackers built a “master key” for a widely used electronic lock, found on millions of hotel room doors. Here’s our story
#:privacy, sicurezza, spionaggio, virus
::: zackwhittaker ::: WIRED ::: FSecure

Researchers Hacked Amazon’s Alexa To Spy On Users, Again
#:privacy, sicurezza, spionaggio, virus
::: Slashdot

North Korea Linked To Global Hacking Operation Against Critical Infrastructure, Telecoms
#:privacy, sicurezza, spionaggio, virus
::: Slashdot

Communities across the U.S. are taking significant steps to ensure transparency and community control over police spy tech
#:privacy, sicurezza, spionaggio, virus
::: EFF

Top 10 Things To Do With #GraalVM
#:linguaggi di programmazione
::: graalvm

Drupal Warns of New Remote-Code Bug, the Second in Four Weeks
#:privacy, sicurezza, spionaggio, virus
::: Slashdot

The Fifth Age Of Macintosh: What Happens If Apple Dumps Intel?
#:ditte #:innovazioni, futuro
::: lucaferrari15

DataExplore is a desktop application for data analysis and plotting intended for use in both research and education
#:applicazioni, programmi
::: cialunet

Appliance Companies Are Lobbying To Protect Their DRM-Fueled Repair Monopolies
#:hardware
::: Slashdot

One undergraduate saw her score plummet to 350 after being named in an unresolved civil suit: Sesame had automatically listed her as a laolai, a deadbeat
#:privacy, sicurezza, spionaggio, virus
::: FrankPasquale

a tutorial about fully abstract compilation
#:programming, codice, snippet
::: wilbowma

I am reading this piece about Ray Ozzie’s key escrow proposal in Wired. A few random thoughts
#:privacy, sicurezza, spionaggio, virus
::: matthew_d_green ::: evacide

Belgium Declares Video Game Loot Boxes Gambling and Therefore Illegal
#:games
::: Slashdot

Answering the most frequently asked questions about Ubuntu 18.04
#:sistemi operativi
::: letozaf

“We are taking a broader view of our responsibility”, Zuckerberg said, which is great, needed, and overdue. But his addition, that FB will “make sure our services are used for good”, is thorny. Who, in diverse+divided societies, gets to decide what’s good?
#:ditte
::: rasmus_kleis

It will take another decade (and another billion dollar research funding) for the Western elite to acknowledge that inequality is the main threat to democracy, not “fake news” or Facebook or Russia. I mean I hope so
#:caos informativo, fake news, bufale #:Web, Internet #:politica
::: h0d3r

Facebook continua a macinare utenti e profitti, in barba a qualunque “scandalo”
#:ditte
::: fabiochiusi ::: FrankPasquale ::: mikko

Get started with Pidgin: An open source replacement for Skype
#:applicazioni, programmi
::: cialunet

CPU utilization is wrong
#:programming, codice, snippet
::: cialunet

Facebook ha comprato una pagina pubblicitaria per comunicare il #Gdpr
#:ditte
::: martinapennisi

Old Lisp programs
bello; ma anche il codice Fortran antico continua a girare (spesso) senza modifiche
#:lisp(s)
::: agambrahma

The new bill to regulate Facebook and Google’s data collection
#:privacy, sicurezza, spionaggio, virus
::: fabiochiusi

La rete zona franca dove tutto è lecito blablabla gli insulti signora mia sono una vergogna blablabla mica come la politica i giornali le tv lì sì che è tutto un galateo e un’eleganza blablabla e ora la parola alla polizia che rimuova blablabla
#:Web, Internet
::: fabiochiusi

Nice features are coming up with Visual Studio this year
#:programming, codice, snippet
::: nicolaiarocci

In the sixties, job ads often specified whether they were looking for men or women. We still advertise jobs by gender in the tech industry–we’re just more subtle about it now
#:ditte
::: proginequality

“This legislation is destined to become a nightmare”. 145 organisations oppose Bulgarian Presidency compromise on the #Copyright in #DSM Directive
#:copyright e brevetti
::: communia_eu

Guida post installazione per Ubuntu 18.04
#:sistemi operativi
::: PinguiniPerCaso

Quick Look at F# in Unity
#:programmazione funzionale
::: thek3nger

A new player among #logging libraries for #Java
#:linguaggi di programmazione
::: fulcorno

Snapchat Takes a Second Try at Spectacles
#:dispositivi mobili
::: Slashdot

Why a touch of secrecy can help creative work
#:programming, codice, snippet
::: lemire

Enlightening article trying to verify leftpad (+2 other small functions) in a range of theorem provers
#:programmazione funzionale
::: _wilfredh

Bests posts on Language Engineering
#:linguaggi di programmazione
::: ftomasse

Fake Mark Zuckerbergs Scam Facebook Users Out of Their Cash
#:caos informativo, fake news, bufale
::: Slashdot

The Smartphone Sales Slowdown is Real
#:dispositivi mobili
::: Slashdot

The new R 3.5.0 brings significant performance and memory improvements
#:linguaggi di programmazione
::: revodavid

New C# Ransomware Compiles Itself at Runtime
#:frodi
::: Slashdot

Grazie del pensiero #Facebook, ma il problema delle #fakenews è esattamente che arrivano a chi non è in grado di distinguere le fonti e interpretare le notizie con cognizione
#:caos informativo, fake news, bufale
::: madbob

Ski Lift In Austria Left Control Panel Open On the Internet
#:privacy, sicurezza, spionaggio, virus
::: Slashdot

Why Oil States is good for open source
#:open source
::: cialunet

Fuchsia OS just showed up in AOSP, but most importantly, in the ART (Android Runtime) branch. Looks like they’re building Fuchsia with ART…which would suggest native Android app support
#:sistemi operativi
::: MishaalRahman

Stack Overflow Isn’t Very Welcoming. It’s Time for That to Change
#:Web, Internet #:programming, codice, snippet
::: JayHanlon

Facebook Inches Toward More Transparency and Accountability
#:ditte
::: Slashdot

Certain products are categorically unethical to deploy. Chief among these is real-time face recognition analysis of live video captured by body-worn cameras
#:privacy, sicurezza, spionaggio, virus
::: FrankPasquale

Report: Freedom of the Press in decline around the world
#:media
::: RadioProzac

Intervista a @massimopolidoro, domani a Lugano per parlare di #bufale e #fakenews
#:caos informativo, fake news, bufale
::: CicapTicino

Dove/come salvare il passato digitale? La formazione di veri “archivi” più urgente che mai
#:storia
::: tedeschini

3 Python template libraries compared
#:linguaggi di programmazione
::: cialunet

Where is serverless computing headed?
#:Web, Internet
::: cialunet

Do you use Ctrl + click or middle-click in Firefox? Maybe you shouldn’t because… it bypasses CSP😂
#:privacy, sicurezza, spionaggio, virus
::: shhnjk

Fabulous Interviews from 2010 with Bletchley Park veterans
#:storia
::: Dr_Black

npm does not support Node.js v10.0.0 You should probably upgrade to a newer version of node as we can’t make any promises that npm will work with this version.
#:linguaggi di programmazione
::: WebReflection

Introiti pubblicitari in forte crescita per Google. Profitti e utenti in crescita per Twitter. Risultati oltre ogni previsione per Facebook, che vola in Borsa. Amazon che raddoppia gli utili e a sua volta vola in Borsa
#:economia
::: fabiochiusi

We can’t agree more! The #censorshipmachine is the worst idea ever!
#:copyright e brevetti #:privacy, sicurezza, spionaggio, virus
::: communia_eu

Issue 69 – The MagPi MagazineThe MagPi Magazine
#:hardware
::: Genjuro75

Sinclair Spectrum designer Rick Dickinson dies
#:storia
::: marcoscan

Sampling profiler written in Rust, using gimli, goblin, and cpp_demangle crates among others
#:programming, codice, snippet
::: fitzgen

If the US empire decays the way the British one did, then it seems plausible that tech/Silicon Valley will do for it what finance/London did for its predecessor, i.e. soften the fall
#:economia
::: evgenymorozov

WhatsApp cifra i contenuti, ma non i dati che li accompagnano. Che sono sfruttabilissimi
#:privacy, sicurezza, spionaggio, virus
::: disinformatico ::: Kantrowitz

A more detailed take on the @EU_Commission Communication on disinformation in thread below, anchored in the most important recommendations from the HLG Report that @Mantzarlis @cjimenezcruz @cward1e and I identified here [thread]
#:caos informativo, fake news, bufale
::: rasmus_kleis

Finally, after a great deal of churn and unexpected obstacles, Hackett supports basic typeclass deriving! 🎉
#:language Racket
::: lexi_lambda ::: lexi_lambda

Full Circle Magazine #132
#:programming, codice, snippet
::: Genjuro75

We’ve lost about ten years of innovation. I feel like this last decade has been pretty boring for the web
#:Web, Internet #:innovazioni, futuro
::: medialab

New research re internet non users in Latin America shows importance of digital literacy
#:Web, Internet #:scuola, educazione
::: hernangalperin

Facebook Inc. is on the hunt for other Cambridge Analytica-sized data leaks, and the company warned Thursday that users and investors might not like what it finds
#:privacy, sicurezza, spionaggio, virus
::: justinhendrix

Clay is on the right side of history, as always
#:privacy, sicurezza, spionaggio, virus
::: evgenymorozov

The only true disclosure is, ‘We sell [or share, or allow access to] your data, and we don’t know where it goes’
#:privacy, sicurezza, spionaggio, virus
::: IEthics

You can’t claim to hire the best if your hiring process turns away engineers who know more than your recruiters
#:programming, codice, snippet
::: sanityinc

Had a great time at the #dagstuhl seminar on algebraic effects this week! Since I was surrounded by veteran FP (mostly Haskell) researchers & practitioners, I asked them to challenge my biases against more extreme forms of FP, such as Monads and category-driven design
thread sconvolgente!
#:programmazione funzionale
::: adriaanm

Oggi a Venezia ho ricordato lo straordinario lavoro – paziente, tenace, pro bono, dietro le quinte – di Giorgio Giunchi, che ha dedicato decenni, fino alla sua morte, a documentare la storia del digitale in Italia
#:storia
::: demartin

Microsoft’s Windows division is no more. Windows made everything the company did possible, but the shift to a post-Windows Microsoft is the right one. To have done the same a decade sooner would have been better
uh! questa è grossassay! 💥💥💥
#:sistemi operativi #:ditte
::: bitfield

Come si fa? C’è nel Web!

Io sono vecchio e il mio modo di lavorare è diverso, non usa tutti questi nuovi strumenti che oggi sono comuni, anzi universalmente considerati indispensabili. Ma poi saltano fuori cose come questo tweet di Joel Spolsky: when you face a problem with code, you should get out a rubber duck and explain, to the duck, exactly how your code was supposed to work [qui]. Cosa che –scusa Joel– credevo di aver inventato io; senza l’ochetta a dire il vero, preferivo torturare un umano. Joel spiega, nel post linkato al cinguettio, tutto quanto per bene, mica devo ripeterlo vero?

Finisce che Joel parla della sua creazione (con Jeff Atwood), Stack Overflow. Io a Stack Overflow chiedo un sacco di cose, anche quando non sarebbe necessario, per esempio “perché mi dà errore ‘startwith‘ in Python?” (risposta: perché non so i verbi). Non ci devo pensare alla mia reputazione su Stack Overflow (molto peggio di niubbo perso–)!

Ma fa anche di più: linka a Stack Overflow question checklist di Jon Skeet, noto come The ‘Chuck Norris’ of programming.

Dice Jon: “Have you read the whole question to yourself carefully, to make sure it makes sense and contains enough information for someone coming to it without any of the context that you already know?” Ecco il mio uso di STack Overflow è inappropriato, solo perché è lì, sempre a portata di mano, sono under-niubbo.

Ma ho un’obiezione da muovere a Jon, Joel &co: la checklist è OK ma vale per chi deve fare domande nuove. Io invece parto dal presupposto che quel che sto chiedendo è già stato chiesto (tante volte) da tanti altri. Di solito funziona. Senza arrivare al copy-paste, anzi spesso modificando il codice per adattarlo al mio caso. Alle volte poi c’è il rimando a un altro URL, per startwith probabilmente m’indirizzerebbe alla documentazione di Python, cioè RTFM. Recentemente mi è capitato che mi ha suggerito il modulo urllib dove c’era proprio quel che cercavo ma nessuno mi aveva detto del modulo.

Forse esco fuori tema ma spesso prima di mettersi a scrivere romanzi alla GRR Martin è buona norma interrogare Stack Overflow, Google, Git*, il Web tutto. Dopo essersi chiarite le idee e aver messo giù su carta lo schema (a meno che sia uno script di poche righe). Forse questa nota è inutile, vale solo per me che una volta… nello scorso millennio… 😐

C’è chi ci fa su dell’umorismo, per esempio qui.

Ma torno da dove ho iniziato. Io non sono più al corrente dello stato dell’arte, come dice John qui. (OK, si riferisce a altro ma la sostanza è quella).

Anche perché sto tentando di approcciarmi a Haskell, con difficoltà. Non solo mie la documentazione è quella che è, nessun paragone con –per esempio– Racket, il linguaggio perfetto con la documentazione perfetta –OK, opinione perso –ma vera 😁

Ho parlato con una haskeller (sì ce ne sono, anche se non ne conosco di qui) che mi ha detto di provare a scrivere codice mio, buttarmici. Ma sono cose da giovani. E per i giovani il tipo di consigli è come questo

Proprio adesso due tweets sull’argomento. Michael (rockz! 💥) confessa che capita anche a lui di dimenticare le cose e googlarci su. Più articolato Jay Hanlon – VP of Stack Overflow: It’s Time for That to Change.

Comincio a disperare di riuscire a postare queste note personali. Perché arriva adesso Stephanie. Anzi chiudo Twitter e metto online il post prima di subito.

👽

Haskell – 181 – monadi – 2

Continuo da qui, copio qui.

La notazione do
We have hinted that there is a connection between monads and the do notation. Here, we make that relationship concrete. There is actually nothing magic about the do notation – it is simply “syntactic sugar” for monadic operations.

As we mentioned earlier, using our Computation class, we could define our above program as:

main =
  readFile "somefile" `augment` \s ->
  putStrLn (show (f s))

But we now know that augment is called >>= in the monadic world. Thus, this program really reads:

main =
  readFile "somefile" >>= \s ->
  putStrLn (show (f s))

And this is completely valid Haskell at this point: if you defined a function f :: Show a => String -> a, you could compile and run this program)

This suggests that we can translate:

x <- f
g x

into f >>= \x -> g x. This is exactly what the compiler does. Talking about do becomes easier if we do not use implicit layout (see the section on Layout [manca ancora] for how to do this). There are four translation rules:

  1. do {e} → e
  2. do {e; es} → e >> do {es}
  3. do {let decls; es} → let decls in do {es}
  4. do {p <- e; es} → let ok p = do {es} ; ok _ = fail "..." in e >>= ok

We will elaborate on these one at a time:

regola di traduzione 1
The first translation rule, do {e} → e, states (as we have stated before) that when performing a single action, having a do or not is irrelevant. This is essentially the base case for an inductive definition of do. The base case has one action (namely e here); the other three translation rules handle the cases where there is more than one action.

regola di traduzione 2
This states that do {e; es} → e >> do {es}. This tells us what to do if we have an action (e) followed by a list of actions (es). Here, we make use of the >> function, defined earlier. This rule simply states that to do {e; es}, we first perform the action e, throw away the result, and then do es.

For instance, if e is putStrLn s for some string s, then the translation of do {e; es} is to perform e (i.e., print the string) and then do es. This is clearly what we want.

regola di traduzione 3
This states that do {let decls; es} → let decls in do {es}. This rule tells us how to deal with lets inside of a do statement. We lift the declarations within the let out and do whatever comes after the declarations.

regola di traduzione 4
This states that do {p <- e; es} → let ok p = do {es} ; ok _ = fail "..." in e >>= ok. Again, it is not exactly obvious what is going on here. However, an alternate formulation of this rule, which is roughly equivalent, is: do {p <- e; es} → e >>= \p -> es. Here, it is clear what is happening. We run the action e, and then send the results into es, but first give the result the name p.

The reason for the complex definition is that p doesn’t need to simply be a variable; it could be some complex pattern. For instance, the following is valid code:

foo = do ('a':'b':'c':x:xs) <- getLine
      putStrLn (x:xs)

In this, we’re assuming that the results of the action getLine will begin with the string “abc” and will have at least one more character. The question becomes what should happen if this pattern match fails. The compiler could simply throw an error, like usual, for failed pattern matches. However, since we’re within a monad, we have access to a special fail function, and we’d prefer to fail using that function, rather than the “catch all” error function. Thus, the translation, as defined, allows the compiler to fill in the ... with an appropriate error message about the pattern matching having failed. Apart from this, the two definitions are equivalent. Non sono sicuro di aver capito –no, aspetta: il codice non è completo, va integrato con la regola 4.

👽

Haskell – 180 – monadi – 1

Continuo da qui, copio qui.

The most difficult concept to master while learning Haskell is that of understanding and using monads. We can distinguish two subcomponents here: (1) learning how to use existing monads and (2) learning how to write new ones. If you want to use Haskell, you must learn to use existing monads. On the other hand, you will only need to learn to write your own monads if you want to become a “super Haskell guru.” Still, if you can grasp writing your own monads, programming in Haskell will be much more pleasant.

So far we’ve seen two uses of monads. The first use was IO actions: We’ve seen that, by using monads, we can get away from the problems plaguing the RealWorld solution to IO presented in the chapter IO [qui e post seguenti]. The second use was representing different types of computations in the section on Classes-computations [qui]. In both cases, we needed a way to sequence operations and saw that a sufficient definition (at least for computations) was:

class Computation c where
  success :: a -> c a
  failure :: String -> c a
  augment :: c a -> (a -> c b) -> c b
  combine :: c a -> c a -> c a

Let’s see if this definition will enable us to also perform IO. Essentially, we need a way to represent taking a value out of an action and performing some new operation on it (as in the example from the section on Functions-io, rephrased slightly):

main = do
  s <- readFile "somefile"
  putStrLn (show (f s))

But this is exactly what augment does. Using augment, we can write the above code as:

main =  -- note the lack of a "do"
  readFile "somefile" `augment` \s ->
  putStrLn (show (f s))

This certainly seems to be sufficient. And, in fact, it turns out to be more than sufficient.

The definition of a monad is a slightly trimmed-down version of our Computation class. The Monad class has four methods (but the fourth method can be defined in terms of the third):

class Monad m where
  return  :: a -> m a
  fail    :: String -> m a
  (>>=)   :: m a -> (a -> m b) -> m b
  (>>)    :: m a -> m b -> m b

In this definition, return is equivalent to our success; fail is equivalent to our failure; and >>= (read: “bind” ) is equivalent to our augment. The >> (read: “then” ) method is simply a version of >>= that ignores the a. This will turn out to be useful; although, as mentioned before, it can be defined in terms of >>=:

a >> x = a >>= \_ -> x

Fin qui sembra tutto OK 😋

👽

AI, innovazioni e blockchain – 19

Cosa ha di bello il venerdì? che sta per arrivare sabato, vero; ma prima la mia rassegna 😋

For more on how algorithms can unfairly limit opportunities, restrict services, & produce “technological redlining,” read this new @datasociety primer
#:algoritmi, codice
::: datasociety

New Alexa Blueprints Let Users Make Custom Skills Without Knowing Any Code
#:artificial intelligence
::: Slashdot

Hackers Keep Robbing Cryptocurrency YouTubers
#:blockchain e crypto*
::: Slashdot

Interesting analogy. But unlike WiFi, which is a technical standard, AI has no agreed-upon meaning
#:artificial intelligence
::: random_walker

MIT engineers have developed a continuous manufacturing process that produces long strips of high-quality graphene
#:innovazioni, futuro
::: Rainmaker1973

Mozilla’s large repository of voice data will shape the future of machine learning
#:machine learning
::: cialunet

Autonomous car platform Apollo doesn’t want you to reinvent the wheel
#:automazione
::: cialunet

AI Can Scour Code To Find Accidentally Public Passwords
#:privacy, sicurezza, spionaggio, virus
::: Slashdot

End of the Landline: BT Aims To Move All UK Customers To VoIP by 2025
#:innovazioni, futuro
::: Slashdot

Which ML algorithm to use
#:machine learning
::: MIT_CSAIL

How #blockchain tech could fix the messy problem of electronic medical records: @DigitalTrends reports on Viral Communications group project MedRec
#:blockchain e crypto*
::: medialab

AI Will Wipe Out Half the Banking Jobs In a Decade, Experts Say
#:artificial intelligence
::: Slashdot

Tutto viene tassato e se non può essere tassato viene proibito
#:blockchain e crypto*
::: libertNation

For years, many people assumed that the decisions algorithms made were objective and neutral. But this is not the case, explained @JuliaAngwin
#:algoritmi, codice
::: journalismfest

Zuckerberg’s promise of AI solutions to Facebook’s ills is just techno-fundamentalism, according to @sivavaid: Solving the last technological problem with more technology—which will just create more problems in turn
#:artificial intelligence
::: ibogost

1/ @ParityTech Substrate, it’s a cool technology stack that you can use to build blockchains and will be the underlying technology for Polkadot. Architected on WebAssembly, sweet!
#:blockchain e crypto*
::: Alexintosh

Recommended reading: Ahead of #MLTalks with Jill Lepore on 4/24 at 3pm, read her 2016 @NewYorker essay “After the Fact,” on truth, politics, and the Internet
#:machine learning
::: medialab

GitHub Launches Bot-Powered Learning Lab for New Developers
#:automazione
::: Slashdot

My take on the reproducibility of academic papers
#:artificial intelligence #:programming, codice, snippet
::: thek3nger

Pantera Capital CEO Says that ‘It’s a Very Good Time to Buy’ Bitcoin
#:blockchain e crypto*
::: JWilliamsFstmed

Intel Is Giving Up On Its Smart Glasses
#:hardware
::: Slashdot

Google’s AR Microscope Quickly Highlights Cancer Cells
#:artificial intelligence
::: Slashdot

Who said fiction was dead? A Gartner study predicts that, “By 2022, the majority of individuals in mature economies will consume more false information than true information.”
#:caos informativo, fake news, bufale #:artificial intelligence
::: FrankPasquale

PSA: there’s a passenger drone IRL!
#:innovazioni, futuro
::: CNET

Technology isn’t an industry, it’s a method of transforming the culture and economics of existing systems and institutions
#:innovazioni, futuro
::: uxzendesign

YAGNI
estremista!
#:artificial intelligence
::: yurrriq

“the Vesta robot could be a sort of mobile Alexa”
“Prototypes of the robots have advanced cameras and computer vision software”
Because who wouldn’t want Amazon eyes “in parts of their home where they don’t have Echo devices”?
#:robots #:artificial intelligence #:privacy, sicurezza, spionaggio, virus
::: fabiochiusi

Open, free and uncensorable websites. The ZeroNet snap provides decentralized websites using Bitcoin crypto and the BitTorrent network 0
#:blockchain e crypto*
::: cialunet

John Oliver on cryptocurrencies: “everything you don’t understand about money combined with everything you don’t understand about computers”
#:blockchain e crypto*
::: nickgrossman

Rolf Maeder

Roundup: five models of federal commissions for AI and robotics
#:artificial intelligence #:robots
::: rcalo

Gary Gensler explained his views on the regulation of blockchain tech and cryptocurrencies
#:blockchain e crypto*
::: medialab

AI Trained on Images from Cosmological Simulations Surprisingly Successful at Classifying Real Galaxies in Hubble Images
#:artificial intelligence
::: Slashdot

Algorithm Automatically Spots ‘Face Swaps’ In Videos
#:artificial intelligence
::: Slashdot

Does AI have a hardware problem?
#:artificial intelligence
::: NatureElectron

Scientists Plan Huge European AI Hub To Compete With US
#:artificial intelligence
::: Slashdot

ProPublica investigative journalist @JuliaAngwin and data scientist @thejefflarson are leaving the company to start a newsroom built around investigating technology and algorithms
#:algoritmi, codice
::: journalismfest

CIA Plans To Replace Spies With AI
#:artificial intelligence
::: Slashdot

Electric Buses Are Hurting the Oil Industry
#:innovazioni, futuro
::: Slashdot

A Study Finds Half of Jobs Are Vulnerable To Automation
#:automazione
::: Slashdot

“The Political Economy of Innovation in China” – new academic article finds that Chinese listed firms’ political connections impede innovation due to ineffective R&D spending
ovviamente da verificare
#:innovazioni, futuro
::: wendyleutert

Nasdaq ‘Would Consider’ Creating a Crypto Exchange, Says CEO
#:blockchain e crypto*
::: Slashdot

Algorithms capable of forming cooperative long-term relationships with people and other machines in arbitrary repeated games are not easy to come by
#:algoritmi, codice
::: FrankPasquale

Bezop Cryptocurrency Server Exposes Personal Info of 25,000 Investors
#:privacy, sicurezza, spionaggio, virus
::: Slashdot

This is from the finance minister of South Korea. Quite incredible. He said alternative payment methods like cryptocurrency (bitcoin, Ethereum, etc.) could replace the fiat system and reserve currencies. He also said crypto market is rapidly growing
#:blockchain e crypto*
::: iamjosephyoung

Amazon Will Now Deliver Packages To the Trunk of Your Car
#:innovazioni, futuro
::: Slashdot

Kazakhstan Is Changing Its Alphabet From Cyrillic To Latin-Based Style Favored By the West
#:innovazioni, futuro
::: Slashdot

Chinese authorities nab fugitive in a crowd of 60k thanks to #facialrecognition
#:artificial intelligence
::: sdallagata

Haskell – 179 – tipi avanzati – 5

Continuo da qui, copio qui.

Genere (kind)
Let us take a moment and think about what types are available in Haskell. We have simple types, like Int, Char, Double and so on. We then have type constructors like Maybe which take a type (like Char) and produce a new type, Maybe Char. Similarly, the type constructor [] (lists) takes a type (like Int) and produces [Int]. We have more complex things like -> (function arrow) which takes two types (say Int and Bool) and produces a new type Int -> Bool.

In a sense, these types themselves have type. Types like Int have some sort of basic type. Types like Maybe have a type which takes something of basic type and returns something of basic type. And so forth.

Talking about the types of types becomes unwieldy and highly ambiguous, so we call the types of types “kinds.” What we have been calling “basic types” have kind “*“. Something of kind * is something which can have an actual value. There is also a single kind constructor, -> with which we can build more complex kinds.

Consider Maybe. This takes something of kind * and produces something of kind *. Thus, the kind of Maybe is * -> *. Recall the definition of Pair from the section on Datatypes-pairs [qui]:

data Pair a b = Pair a b

Here, Pair is a type constructor which takes two arguments, each of kind * and produces a type of kind *. Thus, the kind of Pair is * -> (* -> *). However, we again assume associativity so we just write * -> * -> *.

Let us make a slightly strange datatype definition:

data Strange c a b =
  MkStrange (c a) (c b)

Before we analyze the kind of Strange, let’s think about what it does. It is essentially a pairing constructor, though it doesn’t pair actual elements, but elements within another constructor. For instance, think of c as Maybe. Then MkStrange pairs Maybes of the two types a and b. However, c need not be Maybe but could instead by [], or many other things.

What do we know about c, though? We know that it must have kind * -> *. This is because we have c a on the right hand side. The type variables a and b each have kind * as before. Thus, the kind of Strange is (* -> *) -> * -> * -> *. That is, it takes a constructor (c) of kind * -> * together with two types of kind * and produces something of kind *.

A question may arise regarding how we know a has kind * and not some other kind k. In fact, the inferred kind for Strange is (k -> *) -> k -> k -> *. However, this requires polymorphism on the kind level, which is too complex, so we make a default assumption that k = *.

Note: There are extensions to GHC which allow you to specify the kind of constructors directly. For instance, if you wanted a different kind, you could write this explicitly:

data Strange (c :: (* -> *) -> *) a b = MkStrange (c a) (c b)

to give a different kind to Strange.

The notation of kinds suggests that we can perform partial application, as we can for functions. And, in fact, we can. For instance, we could have:

type MaybePair = Strange Maybe

The kind of MaybePair is, not surprisingly, * -> * -> *.

We should note here that all of the following definitions are acceptable:

type MaybePair1     = Strange Maybe
type MaybePair2 a   = Strange Maybe a
type MaybePair3 a b = Strange Maybe a b

These all appear to be the same, but they are in fact not identical as far as Haskell’s type system is concerned. The following are all valid type definitions using the above:

type MaybePair1a = MaybePair1
type MaybePair1b = MaybePair1 Int
type MaybePair1c = MaybePair1 Int Double

type MaybePair2b = MaybePair2 Int
type MaybePair2c = MaybePair2 Int Double

type MaybePair3c = MaybePair3 Int Double

But the following are not valid:

type MaybePair2a = MaybePair2

type MaybePair3a = MaybePair3
type MaybePair3b = MaybePair3 Int

This is because while it is possible to partially apply type constructors on datatypes, it is not possible on type synonyms. For instance, the reason MaybePair2a is invalid is because MaybePair2 is defined as a type synonym with one argument and we have given it none. The same applies for the invalid MaybePair3 definitions.

Uhmmm… tutto da vedere come si usa.
Il tutorial prevede Gerarchie di classi e Default che ancora mancano. Chissà se… 😐

👽

Haskell – 178 – tipi avanzati – 4

Continuo da qui, copio qui.

Istanze
We have already seen how to declare instances of some simple classes; allow us to consider some more advanced classes here. There is a Functor class defined in the Functor module.

Note: The name “functor”, like “monad” comes from category theory. There, a functor is like a function, but instead of mapping elements to elements, it maps structures to structures.

The definition of the functor class is:

class Functor f where
  fmap :: (a -> b) -> f a -> f b

The type definition for fmap (not to mention its name) is very similar to the function map over lists. In fact, fmap is essentially a generalization of map to arbitrary structures (and, of course, lists are already instances of Functor). However, we can also define other structures to be instances of functors. Consider the following datatype for binary trees:

data BinTree a = Leaf a
               | Branch (BinTree a) (BinTree a)

We can immediately identify that the BinTree type essentially “raises” a type a into trees of that type. There is a naturally associated functor which goes along with this raising. We can write the instance:

instance Functor BinTree where
  fmap f (Leaf a) = Leaf (f a)
  fmap f (Branch left right) =
    Branch (fmap f left) (fmap f right)

Now, we’ve seen how to make something like BinTree an instance of Eq by using the deriving keyword, but here we will do it by hand. We want to make BinTree as instances of Eq but obviously we cannot do this unless a is itself an instance of Eq. We can specify this dependence in the instance declaration:

instance Eq a => Eq (BinTree a) where
  Leaf a == Leaf b = a == b
  Branch l r == Branch l' r' = l == l' && r == r'
  _ == _ = False

The first line of this can be read “if a is an instance of Eq, then BinTree a is also an instance of Eq“. We then provide the definitions. If we did not include the Eq a => part, the compiler would complain because we’re trying to use the == function on as in the second line.

The “Eq a =>” part of the definition is called the “context.” We should note that there are some restrictions on what can appear in the context and what can appear in the declaration. For instance, we’re not allowed to have instance declarations that don’t contain type constructors on the right hand side. To see why, consider the following declarations:

class MyEq a where
  myeq :: a -> a -> Bool

instance Eq a => MyEq a where
  myeq = (==)

As it stands, there doesn’t seem to be anything wrong with this definition. However, if elsewhere in a program we had the definition:

instance MyEq a => Eq a where
  (==) = myeq

In this case, if we’re trying to establish if some type is an instance of Eq, we could reduce it to trying to find out if that type is an instance of MyEq, which we could in turn reduce to trying to find out if that type is an instance of Eq, and so on. The compiler protects itself against this by refusing the first instance declaration.

This is commonly known as the closed-world assumption. That is, we’re assuming, when we write a definition like the first one, that there won’t be any declarations like the second. However, this assumption is invalid because there’s nothing to prevent the second declaration (or some equally evil declaration). The closed world assumption can also bite you in cases like:

class OnlyInts a where
  foo :: a -> a -> Bool

instance OnlyInts Int where
  foo = (==)

bar :: OnlyInts a => a -> Bool
bar = foo 5

We’ve again made the closed-world assumption: we’ve assumed that the only instance of OnlyInts is Int, but there’s no reason another instance couldn’t be defined elsewhere, ruining our definition of bar.

👽

cit. & loll – 93

Anche quando è festa la rassegna arriva puntuale! efficiente me 😋

E le caramelle gommose alla frutta a forma di “like” vuoi non averle!?
::: HackInBo

I’ve definitely worked myself out of a job at least twice
::: bitemyapp

Cat purr genrator
::: Gianlucadfiore

Developer-facing quality is a completely different thing from end-user facing quality, and is usually more important
::: RichRogersIoT

1 hour and 5 diagrams later I optimized 100 lines of code that ran in 13 seconds to 20 lines of heavily vectorized code that runs in 0.02 seconds, and this might just be the best day of my life, so far
::: karpathy

Over my career, my ability to spot errors has improved more than my ability to prevent errors
::: JohnDCook

A true million dollar idea!
::: GiveMeInternet

The key lasting innovation of GitHub/GitLab/etc. might end up being having taught code review to a generation of developers
::: zacchiro

Time flies
::: lizardbill

The Long Journey of Elon Musk
::: Abstruse Goose

Good engineers first understand the ‘why’ & the ‘what’
::: RichRogersIoT

Been chatting to my wife while twitter was down
::: Redpeter99

Yes, AI will create new jobs
::: evgenymorozov

And the sequel: “Undefined Behavior: NaN”
::: peterseibel

The day after tomorrow
::: RichRogersIoT

Which form of OO reuse is most common?
::: RichRogersIoT

The tautological clock sounds like a joke, but it has a precise mathematical background
OK, ma messo qui perché lollosassay 😁
::: Rainmaker1973

“We built this app in 30 minutes with no code.”
::: bketelsen

Zach found an old copy of Ted Nelson’s Computer Lib
::: matthewseiji

All my software projects will have
::: RichRogersIoT

Folks who left tech
::: jesslynnrose

Free drink for coders
::: Rainmaker1973

Tabs vs spaces is nothing. This is the real debate
::: burkeholland

Iteration 💜 Recursion = a match made in heaven… or, you know, #javascript #jsheroes
::: iza_biro

In programming (and in life) there are many ways to achieve a result. Having multiple alternatives is always a good thing, but you really need a compelling reason to deviate from the “standard path” and often this is not the case
::: mariofusco

Avec une petite touche musicale à la fin, merci Charles et Marie Antoinette
uh! come Julia
::: AmelieBenoit33

If you want to kill any idea in the world
::: RichRogersIoT

Over the years I’ve started to prefer code that is boring but easy to understand
::: youyuxi

A stronger type system prevents bugs. But advanced type checkers themselves have bugs
::: TheMichaelBurge

Thing I’m still adjusting to in Haskell: That moment where all your types agree in your editor, you compile in GHC, and suddenly your program does EXACTLY WHAT YOU WANTED
io ci devo ancora arrivare
::: fuzzcat

The central philosophical question of our time
::: KarlreMarks

Inspiration usually comes during work
::: JohnDCook

Writing the code is the easy part
::: xKaliSec

Listening to pro/contra Bitcoin debates in 2018 is so boring, once you have reached a certain level of objective knowledge (not even opinions) the counter arguments sound so dumb and just factually wrong. There are some good arguments but you never hear them there
::: hasufl

you can say anything as long as you put the right emoji next to it
::: kanyewest

I’ve always had a desire to do things people wouldn’t even think to do
::: kanyewest

What five words best describe programming?
::: abstractionscon ::: search?q=https%3A%2F%2Ftwitter.com%2Fabstractionscon%2Fstatus%2F988568678961696769&s=09

Maurizio #Cattelan si fa sponsorizzare la fronte. Si prospettano incredibili possibilità per l’advertising sui calvi
::: SergioGridelli

Code is like humor
::: CodeWisdom

I’m a theorist. I invent equations and then despair over my inability to solve them
non riguarda i ‘puters ma è OK
::: wallingf

An algorithm is just someone’s opinion put in code
::: JennaMC_Laugh

Identify what is wrong with these pictures
::: AaronToponce

Happy bday to Larry Tesler, inventor of “copy-paste”
::: MIT_CSAIL

First you learn the value of abstraction
::: RichRogersIoT