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.

👽

Annunci

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

Haskell – 177 – tipi avanzati – 3

Continuo da qui, copio qui.

Classi
We have already encountered type classes a few times, but only in the context of previously existing type classes. This section is about how to define your own. We will begin the discussion by talking about Pong and then move on to a useful generalization of computations.

Pong
The discussion here will be motivated by the construction of the game Pong (see the appendix on Pong for the full code [manca, forse in futuro…]). In Pong, there are three things drawn on the screen: the two paddles and the ball. While the paddles and the ball are different in a few respects, they share many commonalities, such as position, velocity, acceleration, color, shape, and so on. We can express these commonalities by defining a class for Pong entities, which we call Entity. We make such a definition as follows

class Entity a where
  getPosition :: a -> (Int,Int)
  getVelocity :: a -> (Int,Int)
  getAcceleration :: a -> (Int,Int)
  getColor :: a -> Color
  getShape :: a -> Shape

This code defines a typeclass Entity. This class has five methods: getPosition, getVelocity, getAcceleration, getColor and getShape with the corresponding types.

The first line here uses the keyword class to introduce a new typeclass. We can read this typeclass definition as “There is a typeclass ‘Entity’; a type ‘a’ is an instance of Entity if it provides the following five functions: …”. To see how we can write an instance of this class, let us define a player (paddle) datatype:

data Paddle =
  Paddle { paddlePosX, paddlePosY,
          paddleVelX, paddleVelY,
          paddleAccX, paddleAccY :: Int,
          paddleColor :: Color,
          paddleHeight :: Int,
          playerNumber :: Int }

Given this data declaration, we can define Paddle to be an instance of Entity:

instance Entity Paddle where
  getPosition p = (paddlePosX p, paddlePosY p)
  getVelocity p = (paddleVelX p, paddleVelY p)
  getAcceleration p = (paddleAccX p, paddleAccY p)
  getColor = paddleColor
  getShape = Rectangle 5 . paddleHeight

The actual Haskell types of the class functions all have included the context Entity a =>. For example, getPosition has type Entity a => a -> (Int,Int). However, it will turn out that many of our routines will need entities to also be instances of Eq. We can therefore choose to make Entity a subclass of Eq: namely, you can only be an instance of Entity if you are already an instance of Eq. To do this, we change the first line of the class declaration to:

class Eq a => Entity a where

Now, in order to define Paddles to be instances of Entity we will first need them to be instances of Eq — we can do this by deriving the class.

calcoli
Let’s think back to our original motivation for defining the Maybe datatype. We wanted to be able to express that functions (i.e., computations) can fail.

Let us consider the case of performing search on a graph. Allow us to take a small aside to set up a small graph library:

data Graph v e = Graph [(Int,v)] [(Int,Int,e)]

The Graph datatype takes two type arguments which correspond to vertex and edge labels. The first argument to the Graph constructor is a list (set) of vertices; the second is the list (set) of edges. We will assume these lists are always sorted and that each vertex has a unique id and that there is at most one edge between any two vertices.

Suppose we want to search for a path between two vertices. Perhaps there is no path between those vertices. To represent this, we will use the Maybe datatype. If it succeeds, it will return the list of vertices traversed. Our search function could be written (naively) as follows:

search :: Graph v e -> Int -> Int -> Maybe [Int]
search g@(Graph vl el) src dst
  | src == dst = Just [src]
  | otherwise  = search' el
  where search' [] = Nothing
        search' ((u,v,_):es)
            | src == u  =
              case search g v dst of
                Just p  -> Just (u:p)
                Nothing -> search' es
            | otherwise = search' es

This algorithm works as follows (try to read along): to search in a graph g from src to dst, first we check to see if these are equal. If they are, we have found our way and just return the trivial solution. Otherwise, we want to traverse the edge-list. If we’re traversing the edge-list and it is empty, we’ve failed, so we return Nothing. Otherwise, we’re looking at an edge from u to v. If u is our source, then we consider this step and recursively search the graph from v to dst. If this fails, we try the rest of the edges; if this succeeds, we put our current position before the path found and return. If u is not our source, this edge is useless and we continue traversing the edge-list.

This algorithm is terrible: namely, if the graph contains cycles, it can loop indefinitely. Nevertheless, it is sufficient for now. Be sure you understand it well: things only get more complicated.

Now, there are cases where the Maybe datatype is not sufficient: perhaps we wish to include an error message together with the failure. We could define a datatype to express this as:

data Failable a = Success a | Fail String

Now, failures come with a failure string to express what went wrong. We can rewrite our search function to use this datatype:

search2 :: Graph v e -> Int -> Int -> Failable [Int]
search2 g@(Graph vl el) src dst
  | src == dst = Success [src]
  | otherwise  = search' el
  where search' [] = Fail "No path"
        search' ((u,v,_):es)
          | src == u  =
            case search2 g v dst of
              Success p -> Success (u:p)
              _         -> search' es
          | otherwise = search' es

This code is a straightforward translation of the above.

There is another option for this computation: perhaps we want not just one path, but all possible paths. We can express this as a function which returns a list of lists of vertices. The basic idea is the same:

search3 :: Graph v e -> Int -> Int -> [[Int]]
search3 g@(Graph vl el) src dst
  | src == dst = [[src]]
  | otherwise  = search' el
  where search' [] = []
        search' ((u,v,_):es)
          | src == u  =
               map (u:) (search3 g v dst) ++
               search' es
          | otherwise = search' es

The code here has gotten a little shorter, thanks to the standard Prelude map function, though it is essentially the same.

We may ask ourselves what all of these have in common and try to gobble up those commonalities in a class. In essence, we need some way of representing success and some way of representing failure. Furthermore, we need a way to combine two successes (in the first two cases, the first success is chosen; in the third, they are strung together). Finally, we need to be able to augment a previous success (if there was one) with some new value. We can fit this all into a class as follows:

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

In this class declaration, we’re saying that c is an instance of the class Computation if it provides four functions: success, failure, augment and combine. The success function takes a value of type a and returns it wrapped up in c, representing a successful computation. The failure function takes a String and returns a computation representing a failure. The combine function takes two previous computations and produces a new one which is the combination of both. The augment function is a bit more complex.

The augment function takes some previously given computation (namely, c a) and a function which takes the value of that computation (the a) and returns a b and produces a b inside of that computation. Note that in our current situation, giving augment the type c a -> (a -> a) -> c a would have been sufficient, since a is always [Int], but we make it more general this time just for generality.

How augment works is probably best shown by example. We can define Maybe, Failable and [] to be instances of Computation as:

instance Computation Maybe where
  success = Just
  failure = const Nothing
  augment (Just x) f = f x
  augment Nothing  _ = Nothing
  combine Nothing y = y
  combine x _ = x

Here, success is represented with Just and failure ignores its argument and returns Nothing. The combine function takes the first success we found and ignores the rest. The function augment checks to see if we succeeded before (and thus had a Just something) and, if we did, applies f to it. If we failed before (and thus had a Nothing), we ignore the function and return Nothing.

instance Computation Failable where
  success = Success
  failure = Fail
  augment (Success x) f = f x
  augment (Fail s) _ = Fail s
  combine (Fail _) y = y
  combine x _ = x

These definitions are obvious. Finally:

instance Computation [] where
  success a = [a]
  failure = const []
  augment l f = concat (map f l)
  combine = (++)

Here, the value of a successful computation is a singleton list containing that value. Failure is represented with the empty list and to combine previous successes we simply catenate them. Finally, augmenting a computation amounts to mapping the function across the list of previous computations and concatentate them. we apply the function to each element in the list and then concatenate the results.

Using these computations, we can express all of the above versions of search as:

searchAll g@(Graph vl el) src dst
  | src == dst = success [src]
  | otherwise  = search' el
  where search' [] = failure "no path"
        search' ((u,v,_):es)
          | src == u  = (searchAll g v dst `augment`
                         (success . (u:)))
                        `combine` search' es
          | otherwise = search' es

If you’ve understood this discussion of computations, you are in a very good position as you have understood the concept of monads, probably the most difficult concept in Haskell. In fact, the Computation class is almost exactly the Monad class, except that success is called return, failure is called fail and augment is called >>= (read “bind”). The combine function isn’t actually required by monads, but is found in the MonadPlus class for reasons which will become obvious later.

If you didn’t understand everything here, read through it again and then wait for the proper discussion of monads in the chapter Monads [prossimamente].

👽

Haskell – 176 – tipi avanzati – 2

Continuo da qui, copio qui.

Datatypes
o dovrei tradurre in tipi di dati?

We’ve already seen datatypes used in a variety of contexts. This section concludes some of the discussion and introduces some of the common datatypes in Haskell. It also provides a more theoretical underpinning to what datatypes actually are.

campi rigorosi
One of the great things about Haskell is that computation is performed lazily. However, sometimes this leads to inefficiencies. One way around this problem is to use datatypes with strict fields. Before we talk about the solution, let’s spend some time to get a bit more comfortable with how bottom works in to the picture (for more theory, see the section on Bottom [manca, ancora da fare]).

Suppose we’ve defined the unit datatype (this one of the simplest datatypes you can define):

data Unit = Unit

This datatype has exactly one constructor, Unit, which takes no arguments. In a strict language like ML, there would be exactly one value of type Unit: namely, Unit. This is not quite so in Haskell. In fact, there are two values of type Unit. One of them is Unit. The other is bottom (written ).

Nota: codice Unicode per 8869 o 0x22a5

You can think of bottom as representing a computation which won’t halt. For instance, suppose we define the value:

foo = foo

This is perfectly valid Haskell code and simply says that when you want to evaluate foo, all you need to do is evaluate foo. Clearly this is an “infinite loop.”

What is the type of foo? Simply a. We cannot say anything more about it than that. The fact that foo has type a in fact tells us that it must be an infinite loop (or some other such strange value). However, since foo has type a and thus can have any type, it can also have type Unit. We could write, for instance:

foo :: Unit
foo = foo

Thus, we have found a second value with type Unit. In fact, we have found all values of type Unit. Any other non-terminating function or error-producing function will have exactly the same effect as foo (though Haskell provides some more utility with the function error).

This means, for instance, that there are actually four values with type Maybe Unit. They are: , Nothing, Just ⊥ and Just Unit. However, it could be the fact that you, as a programmer, know that you will never come across the third of these. Namely, you want the argument to Just to be strict. This means that if the argument to Just is bottom, then the entire structure becomes bottom. You use an exclamation point to specify a constructor as strict. We can define a strict version of Maybe as:

data SMaybe a = SNothing | SJust !a

There are now only three values of SMaybe. We can see the difference by writing the following program:

strict.hs

module Main where

import System.Environment  --modif. qui

data SMaybe a = SNothing | SJust !a  deriving Show

main = do
  [cmd] <- getArgs case cmd of "a" -> printJust   undefined
    "b" -> printJust   Nothing
    "c" -> printJust  (Just undefined)
    "d" -> printJust  (Just ())

    "e" -> printSJust  undefined
    "f" -> printSJust  SNothing
    "g" -> printSJust (SJust undefined)
    "h" -> printSJust (SJust ())

printJust :: Maybe () -> IO ()
printJust Nothing = putStrLn "Nothing"
printJust (Just x) = do putStr "Just "; print x

printSJust :: SMaybe () -> IO ()
printSJust SNothing = putStrLn "Nothing"
printSJust (SJust x) = do putStr "Just "; print x

Here, depending on what command line argument is passed, we will do something different. The outputs for the various options are:

$ ghc -o strict strict.hs
[1 of 1] Compiling Main             ( strict.hs, strict.o )
Linking strict ...
$ ./strict a
strict: Prelude.undefined
CallStack (from HasCallStack):
  error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
  undefined, called at strict.hs:10:24 in main:Main
$ ./strict b
Nothing
$ ./strict c
Just strict: Prelude.undefined
CallStack (from HasCallStack):
  error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
  undefined, called at strict.hs:12:29 in main:Main
$ ./strict d
Just ()
$ ./strict e
strict: Prelude.undefined
CallStack (from HasCallStack):
  error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
  undefined, called at strict.hs:15:24 in main:Main
$ ./strict f
Nothing
$ ./strict g
strict: Prelude.undefined
CallStack (from HasCallStack):
  error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
  undefined, called at strict.hs:17:30 in main:Main
$ ./strict h
Just ()

Mica sicuro di aver fatto tutto bene; nel tutorial le segnalazioni sono diverse. Ripensandoci: è OK, Hal non riporta tutto l’output.

The thing worth noting here is the difference between cases “c” and “g”. In the “c” case, the Just is printed, because this is printed before the undefined value is evaluated. However, in the “g” case, since the constructor is strict, as soon as you match the SJust, you also match the value. In this case, the value is undefined, so the whole thing fails before it gets a chance to do anything.

Ci devo pensare su un po’. Ho parlato con una haskeller che mi dice che in sei mesi è diventata ninja 💥; chissà se anch’io… 😐

👽

 

Haskell – 175 – tipi avanzati – 1

Continuo da qui, copio qui.

As you’ve probably ascertained by this point, the type system is integral to Haskell. While this chapter is called “Advanced Types”, you will probably find it to be more general than that and it must not be skipped simply because you’re not interested in the type system.

Sinonimi di tipi
Type synonyms exist in Haskell simply for convenience: their removal would not make Haskell any less powerful.

Consider the case when you are constantly dealing with lists of three-dimensional points. For instance, you might have a function with type [(Double,Double,Double)] -> Double -> [(Double,Double,Double)]. Since you are a good software engineer, you want to place type signatures on all your top-level functions. However, typing [(Double,Double,Double)] all the time gets very tedious. To get around this, you can define a type synonym:

type List3D = [(Double,Double,Double)]

Now, the type signature for your functions may be written List3D -> Double -> List3D.

We should note that type synonyms cannot be self-referential. That is, you cannot have:

type BadType = Int -> BadType

This is because this is an “infinite type.” Since Haskell removes type synonyms very early on, any instance of BadType will be replaced by Int -> BadType, which will result in an infinite loop.

To make a recursive type, one would use newtype:

newtype GoodType = MakeGoodType (Int -> GoodType)

Type synonyms can also be parameterized. For instance, you might want to be able to change the types of the points in the list of 3D points. For this, you could define:

type List3D a = [(a,a,a)]

Then your references to [(Double,Double,Double)] would become List3D Double.

newtypes
Consider the problem in which you need to have a type which is very much like Int, but its ordering is defined differently. Perhaps you wish to order Ints first by even numbers then by odd numbers (that is, all odd numbers are greater than any even number and within the odd/even subsets, ordering is standard).

Unfortunately, you cannot define a new instance of Ord for Int because then Haskell won’t know which one to use. What you want is to define a type which is isomorphic to Int.

Note: “Isomorphic” is a common term in mathematics which basically means “structurally identical.” For instance, in graph theory, if you have two graphs which are identical except they have different labels on the nodes, they are isomorphic. In our context, two types are isomorphic if they have the same underlying structure.

One way to do this would be to define a new datatype:

data MyInt = MyInt Int

We could then write appropriate code for this datatype. The problem (and this is very subtle) is that this type is not truly isomorphic to Int: it has one more value. When we think of the type Int, we usually think that it takes all values of integers, but it really has one more value: (pronounced “bottom”), which is used to represent erroneous or undefined computations. Thus, MyInt has not only values MyInt 0, MyInt 1 and so on, but also MyInt ⊥. However, since datatypes can themselves be undefined, it has an additional value: which differs from MyInt ⊥ and this makes the types non-isomorphic. (See the section on Bottom for more information on bottom. [No, manca, ancora da fare]).

Disregarding that subtlety, there may be efficiency issues with this representation: now, instead of simply storing an integer, we have to store a pointer to an integer and have to follow that pointer whenever we need the value of a MyInt.

To get around these problems, Haskell has a newtype construction. A newtype is a cross between a datatype and a type synonym: it has a constructor like a datatype, but it can have only one constructor and this constructor can have only one argument. For instance, we can define:

newtype MyInt = MyInt Int

But we cannot define any of:

newtype Bad1 = Bad1a Int | Bad1b Double
newtype Bad2 = Bad2 Int Double

Of course, the fact that we cannot define Bad2 as above is not a big issue: we simply use type instead:

type Good2 = Good2 Int Double

or (almost equivalently) declare a newtype alias to the existing tuple type:

newtype Good2 = Good2 (Int,Double)

Now, suppose we’ve defined MyInt as a newtype:

instance Ord MyInt where
  compare (MyInt i) (MyInt j)
    | odd  i && odd  j = compare i j
    | even i && even j = compare i j
    | even i           = LT
    | otherwise        = GT

Like datatype, we can still derive classes like Show and Eq over newtypes (in fact, I’m implicitly assuming we have derived Eq over MyInt — where is my assumption in the above code?).

Moreover, in recent versions of GHC, on newtypes, you are allowed to derive any class of which the base type (in this case, Int) is an instance. For example, we could derive Num on MyInt to provide arithmetic functions over it.

Pattern matching over newtypes is exactly as in datatypes. We can write constructor and destructor functions for MyInt as follows:

mkMyInt i = MyInt i
unMyInt (MyInt i) = i

👽

Visto nel Web – 337

Ecco cosa non è riuscito a sfuggirmi, cosa ho wisto nel Web 💥

Amici e Conoscenti
#:free open source software
::: MadBob

20 years ago this week Sergey Brin and Larry Page published the CS paper that birthed Google
#:storia
::: MIT_CSAIL

TIL the “mame” relay quine now covers 128 languages (and not ‘only’ 100), including NASM, punched tape, MSIL (Mono/.Net) Jasmin (Java bytecode), LLVM…
ultra-super-über 💥
#:linguaggi di programmazione #:umorismo
::: angealbertini

I’m working on a talk called “build impossible things” about writing a program (rbspy!!) that was outside of my comfort zone. so here’s a series of myths about building ambitious-for-you software!
tante idee nel thread 💥
#:programming, codice, snippet
::: b0rk

‘An Apology for the Internet — from the People Who Built It’
#:Web, Internet
::: Slashdot

Pentagon announces 2,000% increase in Russia trolls since Friday
#:sicurezza, spionaggio, virus
::: fabiochiusi

EU #copyright reform proposal to give press publishers an “inalienable right to remuneration” for links and snippets will cause “collateral damage … to our fundamental rights, independent media and European startups”
#:copyright e brevetti
::: rasmus_kleis

Censura FOSTA/SESTA, la soluzione è #Mastodon
vedere tutto il thread
#:censura #:social media
::: madbob

Facebook fuels broad privacy debate by tracking non-users
#:privacy
::: fabiochiusi

One of the people charged for the Reveton ransom trojan was working for Microsoft?
#:frodi
::: mikko

Se questo è davvero il migliore dei mondi possibili, perché siamo così infelici? Un reportage dal TED 2018
non esattamente d’accordo ma riporto
#:Web, Internet
::: RiccardoLuna ::: cmnit

I wrote a new blog post about the internals of Hackett’s new implementation of its type language, and about defining languages with custom core forms in Racket in general
lexi_lambda è ________ di più 💥
#:language Racket #:programmazione funzionale
::: lexi_lambda

Il clima in Ungheria sta diventando davvero irrespirabile. Qui un ricercatore di fama mondiale specialista nella matematica delle reti si scopre in una lista di proscrizione vergata dalla stampa di regime
#:politica
::: cmnit

Lawmakers Call FBI’s ‘Going Dark’ Narrative ‘Highly Questionable’ After Motherboard Shows Cops Can Easily Hack iPhones
#:privacy
::: Slashdot

The Intel Intrinsics Guide https://intel.ly/2H2s7sS (A collection of C style functions that provide access to many Intel instructions without the need to write assembly code)
#:sistemi operativi
::: b3h3m0th

PYthon 2.7.15 release candidate 1 is ready — please test if you still use Python 2!
mah…
#:linguaggi di programmazione
::: gvanrossum ::: Symbo1ics

Former FBI Director James Comey Reveals How Apple and Google’s Encryption Efforts Drove Him ‘Crazy’
#:sicurezza, spionaggio, virus
::: Slashdot

Want to delve into the Python Developers Survey 2017 results to arrive at your own conclusions? Download the raw data and see what you can find!
#:linguaggi di programmazione
::: ThePSF

Excited to see the enthusiasm around open-source. Just don’t forget that most OSS is maintained by people putting in a *lot* of hours and getting very little in return. If our society values this work (and I think it should) we need to find sustainable models for it
#:open source
::: choldgraf

#TheButton – how a woman in #Iceland discovered #Facebook’s global experiment on democracy. My story out now
#:privacy #:sicurezza, spionaggio, virus
::: HNSGR

Facebook’s invisible methods for collecting and generating information on users without their knowledge or consent
#:privacy
::: EFF

China’s Weibo reverses ban on ‘homosexual’ content after outcry
#:Web, Internet
::: fabiochiusi

#Linux is the most widely used OS in the world! Yet so few have found this treasure… Our new #course presents an easy way to test this fabulous operating system. We’ll also introduce you to 4 great distros (@ParrotSec , @ubuntu @Linux_Mint and @elementary )
#:sistemi operativi
::: DLearningS

“Thousands of apps may be tracking the online activity of children in ways that violate US privacy laws, according to a recent survey of Android apps available on the Google Play store“
#:privacy
::: fabiochiusi

YouTube crypto pundit Ian Balina ended a livestream early a short while ago. Since this abrupt end he announced via telegram that he’s been hacked. The lost funds are estimated to be worth $2m
#:pirateria
::: TheAltAnalyst ::: dmtvodka

Tedeschini Lalli: “Come è cambiata l’etica del giornalismo”
moriremo democristiani
#:media
::: tedeschini

Why you should totally switch to #Kotlin
#:linguaggi di programmazione
::: Gianlucadfiore

One of the most rational & articulate critiques of ‘consent’ as a cornerstone for privacy protection you’ll read
#:privacy
::: EUstaran

Russia Begins Blocking Telegram Messenger
#:censura
::: Slashdot

Ban targeted advertising by or for political parties
#:Web, Internet
::: timberners_lee

Happy birthday to LISP, first unveiled in a 1960 paper written @MIT
#:storia #:lisp(s)
::: MIT_CSAIL

Former Senior VP of Apple Tony Fadell Says Company Needs To Tackle Smartphone Addiction
#:dispositivi mobili
::: Slashdot

Ubuntu Studio Plans a Reboot for 18.10 release
#:sistemi operativi
::: dcavedon

France is Building Its Own Encrypted Messaging Service To Ease Fears That Foreign Entities Could Spy on Private Conversations
#:sicurezza, spionaggio, virus
::: Slashdot

California Bill Would Restore, Strengthen Net Neutrality Protections
#:Web, Internet
::: Slashdot

Ho passato buona parte della serata a giocare con #Scratch3 (utilizzabile direttamente online senza scaricare nulla)
#:scuola, educazione #:linguaggi di programmazione
::: madbob

Microsoft Built Its Own Custom Linux Kernel For Its New IoT Service
#:sistemi operativi
::: Slashdot ::: nixcraft ::: cialunet

Build your own web things with the new “Things Framework” from @Mozilla
#:Web, Internet
::: MozillaIoT

Facebook Must Face Class-Action Lawsuit Over Facial Recognition, Says Judge
#:privacy
::: Slashdot

A fully general quantum simulator in 175 lines of self-contained Common #Lisp
#:lisp(s)
::: stylewarning

Hard Questions: What Data Does Facebook Collect When I’m Not Using Facebook, and Why?
#:sicurezza, spionaggio, virus
::: fabiochiusi

Among popular news and current event websites, 66% of tweeted links are made by suspected bots
#:pirateria #:social media
::: fabiochiusi

At least 45 minutes ago, @roscomnadzor formally ordered Apple and Google to remove Telegram from their app stores in Russia. No apparent deadline or ultimatum, however
#:censura
::: KevinRothrock

These Ex-Spies Are Harvesting Facebook Photos For A Massive Facial Recognition Database
#:sicurezza, spionaggio, virus
::: Info_Activism

Cybersecurity Tech Accord: More Than 30 Tech Firms Pledge Not to Assist Governments in Cyberattacks
#:sicurezza, spionaggio, virus
::: Slashdot

Because of course the US and UK know nothing of man-in-the-middle attacks, stealing passwords and credentials and the like
#:sicurezza, spionaggio, virus
::: fabiochiusi

Here’s a generalization of the code in my most recent blog post that handles all fully-expanded expressions and internal-definition contexts. It doesn’t handle module-level contexts because module expansion is extremely complicated
#:programmazione funzionale
::: lexi_lambda

I’m so happy. @GraalVM reached 1.0 today, the JavaScript implementation is open sourced, Graal Python is open sourced; there is a new website with the docs and examples, the community edition binaries are available on GitHub. Congrats, everyone!
da esplorare, sembra über
#:linguaggi di programmazione
::: shelajev ::: thomaswue

Welcome To The (Ubuntu) Bionic Age
#:sistemi operativi
::: dcavedon

One Laptop Per Child’s $100 Laptop Was Going To Change the World — Then it All Went Wrong
#:scuola, educazione #:hardware
::: Slashdot

23 years ago Apache released the Apache HTTP server, an open-source project that serves roughly half of the world’s active websites
#:Web, Internet #:storia
::: MIT_CSAIL

Iterating in batches over data structures can be much faster
#:programming, codice, snippet
::: lemire

di Solus, Gnome e di come visualizzare le thumbnails in Nautilus
#:sistemi operativi #:tip, suggerimenti
::: medeoTL

Writing Arduinobot in Nim
#:hardware #:linguaggi di programmazione
::: Roads Less Taken

Former Cambridge Analytica Employee Says Facebook Users Affected Could Be ‘Much Greater Than 87 million’
#:sicurezza, spionaggio, virus
::: Slashdot

Patrick Stephen, an Illinois teenager who’s created apps to keep track of homework and driver’s ed practice hours, tells @chicagotribune he learned to code with #scratch when he was 7
#:linguaggi di programmazione #:scuola, educazione
::: medialab

A very quirky, but cool af showcase website for Korean GoogleFonts. Basically proves that fonts are sexy
non so a cosa possa servire (qui da noi) ma bellissimissimo 💥💥💥
#:Web, Internet
::: hasdid

Representation in media is a powerful thing
#:media
::: TheSpaceGal

Surveillance capitalists “rely on intimate surveillance of every user to deduce how to emotionally manipulate each person in her own way, and then rent out that information to Russian spies, con artists, racist landlords, and anyone else who will pay up.”
#:sicurezza, spionaggio, virus
::: FrankPasquale

Russian court blocks millions of IP address in attempt to ban Telegram after founder refuses to hand over decryption keys to security services
#:censura
::: wikileaks ::: Slashdot

BuckleScript 3!
#:linguaggi di programmazione
::: reasonml

È stato aggiornato il software di Mars Express
#:programming, codice, snippet
::: quantizzando

Scratch 3.0 preview: nice!
#:scuola, educazione #:linguaggi di programmazione
::: dcavedon

*whispering* despite what programming Twitter says, there are a lot of good reasons that C++ is one of the most widely used programming languages in the world. you shouldn’t feel ashamed to learn how to use C++ in 2018
#:linguaggi di programmazione
::: modocache

Grazie, #Intel, per questa discriminazione tra clienti buoni e clienti cattivi. Complimenti. E no, non servono spiegazioni per un supporto che NON VOLETE fornire
#:ditte
::: MarcoAlici

Sviluppo web e programmazione
tema da sviluppare
#:programming, codice, snippet #:Web, Internet
::: MauroV1968

Racket lets you define “meta-languages” that add features to other languages
#:language Racket
::: TheMichaelBurge

a cool superoptimizer for WebAssembly
#:linguaggi di programmazione
::: johnregehr

The kernel community is about to replace iptables with BPF. I’ve captured my thoughts in a blog post. The performance gains speak for themselves
#:sistemi operativi
::: tgraf__

Different forms of integer division
#:programming, codice, snippet #:matematica
::: hdgarrood

France building encrypted messaging app for politicians
#:sicurezza, spionaggio, virus
::: fabiochiusi

The way that Cambridge Analytica was talking about it, they were viewing it as a means of being able to basically inflict government control and private corporate control over individuals
#:frodi #:politica
::: fabiochiusi

it seems like Facebook is complying with the letter of GDPR law, but with questionable spirit
#:privacy
::: fabiochiusi

6 Python datetime libraries
#:linguaggi di programmazione
::: cialunet

How to install the Moodle learning management system
#:linguaggi di programmazione
::: cialunet

Getting started with Anaconda Python for data science
#:linguaggi di programmazione
::: cialunet

Qt for Python is coming to a computer near you
#:linguaggi di programmazione
::: nicolaiarocci

Alan Kay on Steve Jobs and the Original iPhone
#:storia
::: nicolaiarocci

Mark Zuckerberg’s long game: the next billion
#:social media
::: fabiochiusi

How Facebook Lets Brands and Politicians Target You
#:sicurezza, spionaggio, virus
::: fabiochiusi

Nine of the top 25 websites in the world are now Chinese; just Alibaba alone owns 5 of the top 50 sites
#:Web, Internet
::: mikko

Russia is trying to block Telegram, but it’s failing
#:censura
::: fabiochiusi

Iran Bans State Bodies From Using Telegram App, Khamenei Shuts Account
#:censura
::: Slashdot

Over the course of a few weeks, the countries served by @facebook fact-checking product doubled. And it broke out of Europe and North America
#:privacy
::: Mantzarlis

Facebook “GDPR” settings are mostly set-up to get you to “accept and continue” and go through messy options if you try anything else—and you don’t get full data collection control. This UX design is obviously intentional, driven by the business model. Simple as that
#:privacy
::: zeynep

“I have read and agree to the Terms” is the biggest lie on the web. We aim to fix that
#:sicurezza, spionaggio, virus
::: Info_Activism

I have criticized @telegram’s security model in the past, but @Durov’s response to the Russian government’s totalitarian demand for backdoor access to private communications—refusal and resistance—is the only moral response, and shows real leadership
#:social media
::: Snowden

German government goes open source with cloud firm Nextcloud
#:open source
::: dcavedon

Overview of the Efficient Programming Languages
#:linguaggi di programmazione
::: b3h3m0th

LG’s Linux-based webOS Goes Open Source, Again!
#:sistemi operativi
::: dcavedon

Data Firm Leaks 48 Million User Profiles it Scraped From Facebook, LinkedIn, Others
#:privacy
::: Slashdot ::: fabiochiusi

Interview with @PaniczGodek on Scheme
#:Scheme
::: pldanthony

Dark Money As a Political Sovereignty Problem
#:economia #:politica
::: ProfCiara

Richard Stallman On Facebook’s Privacy Scandal: We Need a Law. There’s No Reason We Should Let Them Exist if the Price is Knowing Everything About Us
#:privacy
::: Slashdot

A Florida Man Has been Accused of Making 97 Million Robocalls
#:spam
::: Slashdot

La ex di mio fratello ha bloccato mia madre su Facebook per non farle vedere in foto le nipotine
#:social media
::: andr900

How should we respond to the Facebook scandal? My proposal: Let’s demand more transparency, and let’s end the arms race to invade our privacy to an ever larger degree in the name of advertising
#:privacy
::: Senficon

Amazon Employee Explains the Poor Working Conditions of An Amazon Warehouse
#:economia
::: Slashdot

Facebook To Design Its Own Processors For Hardware Devices, AI Software, and Servers
#:hardware
::: Slashdot

‘Login With Facebook’ Data Hijacked By JavaScript Trackers
#:sicurezza, spionaggio, virus
::: Slashdot ::: marcelsalathe

Google just created a big problem for anti-censorship tools
#:sicurezza, spionaggio, virus
::: verge

Modern C++ — meaning post-C++11, with auto and foreach and lambdas — is a much more usable language than it used to be, but it still has three major problems and a whole bunch of lesser ones
#:linguaggi di programmazione
::: pathofshrines

Reuters: Facebook to put 1.5 billion users out of reach of new EU privacy law
#:sicurezza, spionaggio, virus
::: marcelsalathe

Lo #Spid ripropone la questione delle competenze digitali. Soprattutto i comuni dovrebbero comprendere l’importanza strategica dell’#AlfabetizzazioneDigitale. Gli strumenti e i volontari ci sono, manca la lungimiranza politica
#:politica
::: SergioGridelli

Facebook says users must accept targeted ads even under new EU law
#:privacy
::: fabiochiusi

Facebook users’ confidence in the company has plunged by 66% as a result of revelations that data analysis firm Cambridge Analytica inappropriately acquired data on tens of millions of Facebook users, a new report reveals
#:ditte
::: NBCNews

5 guiding principles you should know before you design a microservice
#:programming, codice, snippet
::: cialunet

Understanding metrics and monitoring with Python
#:linguaggi di programmazione
::: cialunet

Increasingly, People in Silicon Valley Are Losing Touch With Reality
#:politica
::: Slashdot

We won!!!! German Supreme Court fully confirms that ad blocking in general and @AdblockPlus in particular are 100% legal!
#:ad, pubblicità
::: TimSchu

4.9% of Websites Use Flash, Down From 28.5% in 2011
a me verrebbe voglia di vendicarmi, ecco 👿
#:Web, Internet
::: slashdot

Student: “We’re building a big software system and have been having trouble with one feature
#:linguaggi di programmazione
::: wallingf

Jeff Bezos Reveals That Amazon Has Over 100 Million Prime Subscribers
#:Web, Internet
::: Slashdot

Try my #lisp challenge to write the shortest number sort routine
#:lisp(s)
::: johnson_davies

Palantir’s algorithm alerted the insider threat team when an employee started badging into work later than usual, a sign of potential disgruntlement. That would trigger further scrutiny & possibly physical surveillance after hours by security personnel
#:privacy
::: FrankPasquale

Did you know that Oracle owns the trademark for the word “JavaScript”? No? Did you know they’ve been issuing “cease and desist” orders to conferences, app builders and otherwise? That’s right
#:copyright e brevetti
::: benschwarz

Turn Right at the Burger King: Google Maps Begins Using Landmarks To Help With Guidance
proprio come gli umani
#:innovazioni, futuro
::: Slashdot

Linux async I/O
#:programming, codice, snippet
::: danluu

Palantir Knows Everything About You
#:sicurezza, spionaggio, virus
::: marcelsalathe

Over 60 years ago today researchers ran the first FORTRAN program, considered the beginning of general-purpose programming
#:storia
::: MIT_CSAIL

Do you know how a PCB is made? Go inside the fab and see how @CircuitClassics were manufactured
#:hardware
::: starsandrobots

By how much does AVX-512 slow down your CPU? A first experiment
#:programming, codice, snippet
::: lemire

IBM System 360/195 (1971) operating console
#:storia
::: 8bitkick

Millions of Chrome Users Have Installed Malware Posing as Ad Blockers
#:sicurezza, spionaggio, virus
::: Slashdot

un po’ troppi problemi con #npm si risolvono in “cancella la cartella node_modules e reinstalla tutto daccapo”
#:linguaggi di programmazione
::: madbob

90% of what passes for “serious debate about the future of the Internet” in the US is just desperate liberal academics
#:Web, Internet
::: evgenymorozov

Where we’re at with Facebook
#:social media
::: annamasera

1. Facebook moves their business to Ireland for advantageous tax environment
#:ditte
::: mcclure111

After Cambridge Analytica, PricewaterhouseCoopers, on behalf of Facebook, reported to the FTC that privacy compliances at Facebook were fine and there were no problems
#:sicurezza, spionaggio, virus
::: fabiochiusi

Beyond Cambridge Analytica — The Surveillance Companies Infiltrating And Manipulating Social Media
#:sicurezza, spionaggio, virus
::: CBlengio

Audit Approved of Facebook Policies, Even After Cambridge Analytica Leak
#:sicurezza, spionaggio, virus
::: Slashdot

If the “government social media experts” are going to blind brief scary stories about RUSSIAN BOTS apparently influencing people post-Skripal and Douma, the least they could do is release some of the examples
#:caos informativo, fake news, bufale #:politica
::: MarkDiStef

For a long time we have said that Article 13 is dangerous and should be deleted. Now even the rightsholders (@CreativityW) are starting to wake up to the reality that it will cause more harm than good. @EP_Legal can we please start over?
#:copyright e brevetti
::: communia_eu

hours before testifying in front of congress, FB sends emails out to conservatives enlisting their help against pushing back on GDPR-style privacy regulations in the United States
#:ditte
::: MikeIsaac

It’s just facebook. You’re reinventing Facebook…
#:social media
::: hakimrah

cd is Wasting Your Time
sì j è über, altamente raccomandato per chi usa il terminale
#:tools, componenti software
::: LRazovic

#els2018 was awesome! Now it’s time to hack some Lisp! An experimental implementation of blocking functions (read, sleep, …)
#:lisp(s) #:Web, Internet
::: davazp

UK government falsely accuses two Twitter users of being Kremlin bots and the Guardian reprints without fact checking. Both users say they are now considering suing. One, @Partisangirl is a very well known Syrian Youtuber in Australia.
#:caos informativo, fake news, bufale #:politica
::: wikileaks

Falsa Ico di Telegram, ecco i siti che hanno ingannato migliaia di utenti
#:frodi
::: dcavedon

Compilers 109 – Parser. (The latest article about Compilers)
#:programming, codice, snippet
::: b3h3m0th

Democratic Party Files Suit Alleging Russia, the Trump Campaign, and WikiLeaks Conspired To Disrupt the 2016 Election
#:sicurezza, spionaggio, virus #:politica
::: Slashdot

DOSBox-X is a x86 emulator with Tandy/Hercules/CGA/EGA/VGA/SVGA graphics sound and DOS. It’s been designed to run old DOS games under platforms that don’t support it. Ready to install as a snap for #ubuntu
#:sistemi operativi
::: cialunet

Kaspersky Lab Banned From Advertising on Twitter Because of Its Alleged Ties With Russian Intelligence Agencies
#:sicurezza, spionaggio, virus
::: Slashdot

Users Don’t Want iOS To Merge With MacOS, Apple Chief Tim Cook Says
#:sistemi operativi
::: Slashdot

I’m that “#RussianBot” the @guardian and the British government warned you about
#:caos informativo, fake news, bufale #:politica
::: Partisangirl

Is Facebook spying on you?
cerrrto!
#:privacy
::: verge

Ho googlato il nome dello scienziato americano che oggi dalle pagine di Repubblica ci informa che le notifiche sul cellulare sono come l’oppio
è di carta, dev’essere una cosa seria 😋
#:caos informativo, fake news, bufale
::: mante

FastPriorityQueue.js (new release: 0.4.0) a fast heap-based priority queue in JavaScript
#:linguaggi di programmazione
::: lemire

This is how Facebook collects data on you even if you don’t have an account. And there’s little you can do to stop it
#:privacy
::: Recode

Really excited to be teaching @rustlang to 450+ undergrads in CMSC 330. First two lectures, and project, are up!
#:linguaggi di programmazione
::: michael_w_hicks

You have to get in with the right angel investors or incubator at the start. And they’re just a small number, it’s like a social order. And then the output on the other side is usually being acquired by one of a very small number of top companies
riporto, nèh!
#:Web, Internet
::: FrankPasquale

New Facebook terms of service to prepare for #GDPR, two choices: accept it or remove the account
#:ditte
::: lukOlejnik

Not all phone activity relate to digital engagement: introducing Phone Boredom
#:dispositivi mobili
::: TNLNYC

So, this is weird. Gmail has started inserting zero-width unicode spaces in random parts of outgoing emails. Anyone have any idea what this is about?
#:Web, Internet
::: dwlz

Haskell – 174 – Sintassi avanzata – 11

Continuo da qui, copio qui.

Il tutorial prevede la sezione Layout ancora tutta da fare, chissà se prossimamente 😉

Conclusioni sulle liste
You are likely tired of hearing about lists at this point, but they are so fundamental to Haskell (and really all of functional programming) that it would be terrible not to talk about them some more.

It turns out that foldr is actually quite a powerful function: it can compute a primitive recursive function. A primitive recursive function is essentially one which can be calculated using only “for” loops, but not “while” loops.

In fact, we can fairly easily define map in terms of foldr:

map2 f = foldr (\a b -> f a : b) []

Here, b is the accumulator (i.e., the result list) and a is the element being currently considered. In fact, we can simplify this definition through a sequence of steps:

     foldr (\a b -> f a : b) []
==>  foldr (\a b -> (:) (f a) b) []
==>  foldr (\a -> (:) (f a)) []
==>  foldr (\a -> ((:) . f) a) []
==>  foldr ((:) . f) []

This is directly related to the fact that foldr (:) [] is the identity function on lists. This is because, as mentioned before, foldr f z can be thought of as replacing the [] in lists by z and the : by f. In this case, we’re keeping both the same, so it is the identity function.

In fact, you can convert any function of the following style into a foldr:

myfunc [] = z
myfunc (x:xs) = f x (myfunc xs)

By writing the last line with f in infix form, this should be obvious:

myfunc [] = z
myfunc (x:xs) = x `f` (myfunc xs)

Clearly, we are just replacing [] with z and : with f. Consider the filter function:

filter p [] = []
filter p (x:xs) =
  if p x
    then x : filter p xs
    else filter p xs

This function also follows the form above. Based on the first line, we can figure out that z is supposed to be [], just like in the map case. Now, suppose that we call the result of calling filter p xs simply b, then we can rewrite this as:

filter p [] = []
filter p (x:xs) =
  if p x then x : b else b

Given this, we can transform filter into a fold:

filter p = foldr (\a b -> if p a then a:b else b) []

Let’s consider a slightly more complicated function: ++. The definition for ++ is:

(++) []     ys = ys
(++) (x:xs) ys = x : (xs ++ ys)

Now, the question is whether we can write this in fold notation. First, we can apply eta reduction to the first line to give (++) [] = id.

Through a sequence of steps, we can also eta-reduce the second line:

     (++) (x:xs) ys = x : ((++) xs ys)
==>  (++) (x:xs) ys = (x:) ((++) xs ys)
==>  (++) (x:xs) ys = ((x:) . (++) xs) ys
==>  (++) (x:xs) = (x:) . (++) xs

Thus, we get that an eta-reduced definition of ++ is:

(++) []     = id
(++) (x:xs) = (x:) . (++) xs

Now, we can try to put this into fold notation. First, we notice that the base case converts [] into id. Now, if we assume (++) xs is called b and x is called a, we can get the following definition in terms of foldr:

(++) = foldr (\a b -> (a:) . b) id

This actually makes sense intuitively. If we only think about applying ++ to one argument, we can think of it as a function which takes a list and creates a function which, when applied, will prepend this list to another list. In the lambda function, we assume we have a function b which will do this for the rest of the list and we need to create a function which will do this for b as well as the single element a. In order to do this, we first apply b and then further add a to the front.

We can further reduce this expression to a point-free style through the following sequence:

==>  (++) = foldr (\a b -> (a:) . b) id
==>  (++) = foldr (\a b -> (.) (a:) b) id
==>  (++) = foldr (\a -> (.) (a:)) id
==>  (++) = foldr (\a -> (.) ((:) a)) id
==>  (++) = foldr (\a -> ((.) . (:)) a) id
==>  (++) = foldr ((.) . (:)) id

This final version is point free, though not necessarily understandable. Presumbably the original version is clearer.

As a final example, consider concat. We can write this as:

concat []     = []
concat (x:xs) = x ++ concat xs

It should be immediately clear that the z element for the fold is [] and that the recursive function is ++, yielding concat = foldr (++) [].

esercizi
1. The function and takes a list of booleans and returns True if and only if all of them are True. It also returns True on the empty list. Write this function in terms of foldr.

We can start out with a recursive definition:

and [] = True
and (x:xs) = x && and xs

From here, we can clearly rewrite this as and = foldr (&&) True.

2. The function concatMap behaves such that concatMap f is the same as concat . map f. Write this function in terms of foldr.

We can write this recursively as:

concatMap f [] = []
concatMap f (x:xs) = f x ++ concatMap f xs

This hints that we can write this as concatMap f = foldr (\a b -> f a ++ b) [].

Now, we can do point elimination to get:

     foldr (\a b -> f a ++ b) []
==>  foldr (\a b -> (++) (f a) b) []
==>  foldr (\a -> (++) (f a)) []
==>  foldr (\a -> ((++) . f) a) []
==>  foldr ((++) . f) []

👽

Haskell – 173 – Sintassi avanzata – 10

Continuo da qui, copio qui.

Mappe
Un’avvertenza dal prof (Hal rockz! 💥): This section is work in progress, please help improving it! Il PDF è diverso ma non mi sembra più aggiornato; anzi fa riferimento a FiniteMap che non trovo nella documentazione, forse roba vecchia.

The Map datatype from the Data.Map module is a purely functional implementation of balanced trees. Maps can be compared to lists and arrays in terms of the time it takes to perform various operations on those datatypes of a fixed size, n. A brief comparison is:

As we can see, lists provide fast insertion (but slow everything else), arrays provide fast lookup (but slow everything else) and maps provide moderately fast everything.

The type of a map is for the form Map k a where k is the type of the keys and a is the type of the elements. That is, maps are lookup tables from type k to type a.

The basic map functions are:

empty  :: Map k a
insert :: k -> a -> Map k a -> Map k a
delete :: k -> Map k a -> Map k a
member :: k -> Map k a -> Bool
lookup :: k -> Map k a -> a

In all these cases, the type k must be an instance of Ord (and hence also an instance of Eq).

There are also function fromList and toList to convert lists to and from maps. Try the following:

Prelude> :m Data.Map
Prelude Data.Map> let mymap = fromList [('a',5),('b',10),('c',1),('d',2)]
Prelude Data.Map> let othermap = insert 'e' 6 mymap
Prelude Data.Map> toList mymap
[('a',5),('b',10),('c',1),('d',2)]
Prelude Data.Map> toList othermap
[('a',5),('b',10),('c',1),('d',2),('e',6)]
Prelude Data.Map> Data.Map.lookup 'e' othermap
Just 6
Prelude Data.Map> Data.Map.lookup 'e' mymap
Nothing

👽

AI, innovazioni e blockchain – 18

Succedono sempre cose nuove, ecco quelle che non mi sono scappate

un dr. molto saggio

Researchers Devise a Way To Generate Provably Random Numbers Using Quantum Mechanics
#:innovazioni, futuro
::: Slashdot

Crypto currencies are the new oil shares #disinvest
#:blockchain e crypto*
::: marcelsalathe

Lant Pritchett’s 6 surprising (and often unwelcome) things you need to hear about development
#:economia #:innovazioni, futuro
::: TimHarford

World’s First Electrified Road For Charging Vehicles Opens In Sweden
#:innovazioni, futuro
::: Slashdot

438 Bitcoins Worth Nearly $3.5 Million Stolen From Exchange In India, CSO Accused
#:blockchain e crypto*
::: Slashdot

Trump Orders Audit of Postal Service After Suggesting Amazon Is To Blame For Their Troubles
#:economia
::: Slashdot

I have the impression that people are looking at machine learning in gamedev from a completely wrong angle. (well, no angle is really wrong, but… whatever)
#:machine learning
::: thek3nger

Trade War Or Not, China is Closing the Gap on US in Technology IP Race
#:innovazioni, futuro #:economia
::: Slashdot

“Democracy has a bad user interface.” At #TED2018, @CollectiveMIT head @cesifoti imagines a system of direct democracy fueled by personalized digital agents that vote on issues for us
#:innovazioni, futuro #:politica
::: medialab

Ma cos’è l’industria “tech”?
#:innovazioni, futuro
::: MauroV1968

The Long, Slow Demise of Credit Card Signatures Starts Today
#:innovazioni, futuro
::: Slashdot

AI Can Generate a 3D Model of a Person After Watching a Few Seconds of Video
#:artificial intelligence
::: Slashdot

Google’s New Book Search Deals in Ideas, Not Keywords
#:Web, Internet
::: Slashdot

Yes, excessive automation at Tesla was a mistake. To be precise, my mistake. Humans are underrated
#:automazione
::: elonmusk

The computer ceased to be a servant of human life and began to be the purpose for which that life is conducted
#:artificial intelligence
::: ibogost

Robots Replace Soldiers In First of Its Kind Obstacle-Breaching Exercise
#:artificial intelligence
::: Slashdot

@elonmusk agrees that Tesla is relying on too many robots to make the Model 3 & needs more workers
#:robots
::: timkhiggins

This is how Bitcoin works
#:blockchain e crypto*
::: medialab

European Parliament proposes to grant personhood status to robots. 🤦‍♀️ Experts say nah
#:robots
::: ncilla

The Impact of Artificial Intelligence on Innovation
#:artificial intelligence
::: Slashdot

Cambridge Analytica scandal ‘highlights need for AI regulation’
#:artificial intelligence
::: fabiochiusi

Ola Wants a Million Electric Rides on India’s Roads by 2021
#:innovazioni, futuro
::: Slashdot

The perfect #Bitcoin ⚡️Lightning⚡ node #RaspberryPi #experiment
#:blockchain e crypto*
::: orfeomorello

Italy just lost the #blockchain trein. I couldn’t have been more disappointed
#:blockchain e crypto*
::: Alexintosh

Introducing GapminderVR: Data Visualization in Virtual Reality
#:innovazioni, futuro
::: lemire

Hackers stole a casino’s high-roller database through a thermometer in the lobby fish tank
#:Internet of things
::: AkiAnastasiou

MIT machine-learning system automatically maps roads using aerial images
#:machine learning
::: MIT_CSAIL

The first blockchain university
#:blockchain e crypto*
::: lemire

Selling Full Autonomy Before It’s Ready Could Backfire For Tesla
#:automazione
::: Slashdot

New York’s Attorney General Is Investigating Bitcoin Exchanges
#:blockchain e crypto*
::: Slashdot

Taste is increasingly dictated by algorithms
#:algoritmi, codice
::: laura_nobilis

FDA Approves First Contact Lenses That Turn Dark In Bright Sunlight
#:innovazioni, futuro
::: Slashdot

Cambridge Analytica Planned To Launch Its Own Cryptocurrency
#:blockchain e crypto*
::: Slashdot

Eclipse 2018 survey: The IoT landscape, what it empirically looks like
#:Internet of things
::: cialunet

Every major tech innovation of the last 150 years — and how they’ve improved productivity
#:storia #:innovazioni, futuro
::: MIT_CSAIL

A short blockchain story
#:blockchain e crypto* #:umorismo
::: vexmark

If you’ve become wealthy by selling your Bitcoins, pay your taxes!
#:blockchain e crypto*
::: mikko

Today I am excited to announce that @JinMan and I have launched our Industrial IoT start-up
#:Internet of things
::: RichRogersIoT

The pace of technology is accelerating. Hardware manufacturers will soon utilize incoming IoT data to determine how products are deployed & consumed. This data will directly influence how products are designed & manufactured in a more real-time manner
#:Internet of things
::: RichRogersIoT

German ICO Savedroid Pulls Exit Scam After Raising $50 Million
#:blockchain e crypto*
::: Slashdot

MIT Discovers Way To Mass-Produce Graphene In Large Sheets
#:innovazioni, futuro
::: Slashdot

Autonomous Boats Will Be On the Market Sooner Than Self-Driving Cars
#:automazione
::: Slashdot

Scientists Create Robots That Can Assemble IKEA Furniture For You
#:robots
::: Slashdot

Amazon filed a patent to de-anonymize Bitcoin transactions and sell the data to law enforcement
#:blockchain e crypto* #:sicurezza, spionaggio, virus
::: x0rz

Artificial Intelligence — The Revolution Hasn’t Happened Yet
#:artificial intelligence
::: drfeifei

The suspected mastermind behind the theft of 600 computers used to mine bitcoin in Iceland has escaped from prison and fled to Sweden on an aeroplane reportedly carrying the Icelandic prime minister
#:blockchain e crypto*
::: dueledge

The risks of an insecure #IoT device extend far beyond the buyer’s own network
#:Internet of things
::: cialunet

Big news today! I’ve founded Ursa Labs, a development lab for open source data science, powered by @ApacheArrow
#:innovazioni, futuro
::: wesmckinn ::: rstudio

Haskell – 172 – Sintassi avanzata – 9

Continuo da qui, copio qui.

Arrays
Lists are nice for many things. It is easy to add elements to the beginning of them and to manipulate them in various ways that change the length of the list. However, they are bad for random access, having average complexity O(n) to access an arbitrary element (if you don’t know what O(...) means, you can either ignore it or take a quick detour and read the appendix chapter Complexity [prossimamente], a two-page introduction to complexity theory). So, if you’re willing to give up fast insertion and deletion because you need random access, you should use arrays instead of lists.

In order to use arrays you must import the Array module. There are a few methods for creating arrays, the array function, the listArray function, and the accumArray function. The array function takes a pair which is the bounds of the array, and an association list which specifies the initial values of the array. The listArray function takes bounds and then simply a list of values. Finally, the accumArray function takes an accumulation function, an initial value and an association list and accumulates pairs from the list into the array. Here are some examples of arrays being created:

Prelude> import Data.Array
Prelude Data.Array> array (1,5) [(i,2*i) | i <- [1..5]] 
array (1,5) [(1,2),(2,4),(3,6),(4,8),(5,10)] 
Prelude Data.Array> listArray (1,5) [3,7,5,1,10]
array (1,5) [(1,3),(2,7),(3,5),(4,1),(5,10)]
Prelude Data.Array> accumArray (+) 2 (1,5) [(i,i) | i <- [1..5]]
array (1,5) [(1,3),(2,4),(3,5),(4,6),(5,7)]

When arrays are printed out (via the show function), they are printed with an association list. For instance, in the first example, the association list says that the value of the array at 1 is 2, the value of the array at 2 is 4, and so on.

You can extract an element of an array using the ! function, which takes an array and an index, as in:

Prelude Data.Array> (listArray (1,5) [3,7,5,1,10]) ! 3
5

Moreover, you can update elements in the array using the // function. This takes an array and an association list and updates the positions specified in the list:

Prelude Data.Array> (listArray (1,5) [3,7,5,1,10]) // [(2,99),(3,-99)]
array (1,5) [(1,3),(2,99),(3,-99),(4,1),(5,10)]

There are a few other functions which are of interest:

bounds returns the bounds of an array
indices returns a list of all indices of the array
elems returns a list of all the values in the array in order
assocs returns an association list for the array

If we define arr to be listArray (1,5) [3,7,5,1,10], the result of these functions applied to arr are:

Prelude Data.Array> arr = listArray (1,5) [3,7,5,1,10]
Prelude Data.Array> bounds arr
(1,5)
Prelude Data.Array> indices arr
[1,2,3,4,5]
Prelude Data.Array> elems arr
[3,7,5,1,10]
Prelude Data.Array> assocs arr
[(1,3),(2,7),(3,5),(4,1),(5,10)]

Note that while arrays are O(1) access, they are not O(1) update. They are in fact O(n) update, since in order to maintain purity, the array must be copied in order to make an update. Thus, functional arrays are pretty much only useful when you’re filling them up once and then only reading. If you need fast access and update, you should probably use FiniteMaps, which are discussed in the section on Finitemaps [che non trovo, forse manca ancora] and have O(log n) access and update.

👽