Haskell – 62 – sintassi nelle funzioni – 2

Continuo da qui, copio qui.

Guardie
Whereas patterns are a way of making sure a value conforms to some form and deconstructing it, guards are a way of testing whether some property of a value (or several of them) are true or false. That sounds a lot like an if statement and it’s very similar. The thing is that guards are a lot more readable when you have several conditions and they play really nicely with patterns.

Instead of explaining their syntax, let’s just dive in and make a function using guards. We’re going to make a simple function that berates you differently depending on your BMI (body mass index). Your BMI equals your weight divided by your height squared. If your BMI is less than 18.5, you’re considered underweight. If it’s anywhere from 18.5 to 25 then you’re considered normal. 25 to 30 is overweight and more than 30 is obese. So here’s the function (we won’t be calculating it right now, this function just gets a BMI and tells you off)

bmi.hs

bmiTell :: (RealFloat a) => a -> String
bmiTell bmi
  | bmi <= 18.5 = "You're underweight, you emo, you!"
  | bmi <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!"
  | bmi <= 30.0 = "You're fat! Lose some weight, fatty!"
  | otherwise   = "You're a whale, congratulations!"

Guards are indicated by pipes that follow a function’s name and its parameters. Usually, they’re indented a bit to the right and lined up. A guard is basically a boolean expression. If it evaluates to True, then the corresponding function body is used. If it evaluates to False, checking drops through to the next guard and so on. If we call this function with 24.3, it will first check if that’s smaller than or equal to 18.5. Because it isn’t, it falls through to the next guard. The check is carried out with the second guard and because 24.3 is less than 25.0, the second string is returned.

This is very reminiscent of a big if else tree in imperative languages, only this is far better and more readable. While big if else trees are usually frowned upon, sometimes a problem is defined in such a discrete way that you can’t get around them. Guards are a very nice alternative for this.

Many times, the last guard is otherwise. otherwise is defined simply as otherwise = True and catches everything. This is very similar to patterns, only they check if the input satisfies a pattern but guards check for boolean conditions. If all the guards of a function evaluate to False (and we haven’t provided an otherwise catch-all guard), evaluation falls through to the next pattern. That’s how patterns and guards play nicely together. If no suitable guards or patterns are found, an error is thrown.

Of course we can use guards with functions that take as many parameters as we want. Instead of having the user calculate his own BMI before calling the function, let’s modify this function so that it takes a height and weight and calculates it for us.

bmi-1.hs

bmiTell :: (RealFloat a) => a -> a -> String
bmiTell weight height
  | weight / height ^ 2 <= 18.5 = "You're underweight, you emo, you!"
  | weight / height ^ 2 <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!"
  | weight / height ^ 2 <= 30.0 = "You're fat! Lose some weight, fatty!"
  | otherwise = "You're a whale, congratulations!"

Let’s see if I’m fat …

*Main> :l bmi-1
[1 of 1] Compiling Main             ( bmi-1.hs, interpreted )
Ok, modules loaded: Main.
*Main> bmiTell 95 1.80
"You're fat! Lose some weight, fatty!"

Yes, I know. But Haskell just called me fatty. Whatever!

Note that there’s no = right after the function name and its parameters, before the first guard. Many newbies get syntax errors because they sometimes put it there.

Another very simple example: let’s implement our own max function. If you remember, it takes two things that can be compared and returns the larger of them.

max' :: (Ord a) => a -> a -> a
max' a b
  | a > b     = a
  | otherwise = b

Guards can also be written inline, although I’d advise against that because it’s less readable, even for very short functions. But to demonstrate, we could write max' like this:

max' :: (Ord a) => a -> a -> a
max' a b | a > b = a | otherwise = b

Ugh! Not very readable at all! Moving on: let’s implement our own compare by using guards.

comp.hs

myCompare :: (Ord a) => a -> a -> Ordering
a `myCompare` b
  | a > b     = GT
  | a == b    = EQ
  | otherwise = LT
*Main> :l comp
[1 of 1] Compiling Main             ( comp.hs, interpreted )
Ok, modules loaded: Main.
*Main> 3 `myCompare` 2
GT
*Main> 3 `myCompare` 5
LT
*Main> myCompare 8 8
EQ

Note: Not only can we call functions as infix with backticks, we can also define them using backticks. Sometimes it’s easier to read that way.

🤩

Annunci

cit. & loll – 74

Quasi ora di entrare nella stagione delle feste, fare festa perché finisce quest’anno –ma attenzione, il prossimo difficilmente sarà meglio. E saremo più vecchi 😡 Boh! intanto ecco cose citose e lollose 😋

Self-Driving Car Milestones
::: xkcd

sed “/bam/ s/foo/bar/” # Replace foo with bar only on lines that contain ‘bam’
::: climagic

In the end, regardless of where you are on the development hierarchy, keep coding.
::: CodeWisdom

Sure, Perl, why not? That makes sense
::: lizardbill

Once a new technology rolls over you
::: CodeWisdom

Bitcoin was supposed to demonstrate the power of a true free market
::: adam_chal

One of the truest things in systems design
::: marius

FT on Bitcoin
::: keleshev

98% of people have strong, unconscious biases
::: wallingf

9 Dev lies
::: RichRogersIoT

Parlano di bolle, Bitcoin e criptomenete in generale quando non sanno neanche cosa sia una Blockchain e non hanno la minima nozione di Econonia
::: LRazovic ::: Donearm ::: Slashdot ::: InternetHippo ::: amasad ::: Slashdot

What business model explains that hundreds of beautiful ladies are trying chat with me on Google Hangout?
::: lemire

Programmers should never be satisfied with languages
::: CodeWisdom

dear world: the next time Zuckerberg, Tim May, O’Reilly, …
::: dgolumbia

cannibali

Always wanted to travel back in time to try fighting a younger version of yourself?
::: RichRogersIoT

It took me a while to grasp that a Haskell program
::: a4dev

Oh dear. European Parliament @EP_Legal discussing this morning whether 3D printing will allow us
::: Senficon

Fausses nouvelles (Fake NEWS)
::: glipari

Bad Code
::: xkcd

I’m investing in Bitcoin because what I’m looking for is the market volatility
::: jodamico1

4.5 megabytes of data in 62,500 punched cards, USA, 1955
::: oldpicsarchive

Bitcoin, it’s like real money
::: internetofshit

Bitcoin is a fucking joke
::: arrdem

The function of good software
::: RichRogersIoT

Program testing can be a very effective way to show the presence of bugs
::: CodeWisdom

Non son i russi quelli avanzatissimi
::: Genjuro75

I have yet to see any problem, however complicated, which, when you looked at it in the right way
::: CodeWisdom

I hadn’t had much coding experience, so I asked him what language I should learn…
::: jakevdp

Poi ditemi voi come si fa a non amare quelle spie russe di @valigiablu
::: fabiochiusi

That moment when you look at the price of bitcoin and think it can’t go any higher
::: levie

LinkedIn emerging jobs report 2017: Tech is king
::: epfl_exts

Bitcoin: 8.27 terawatt-hours
::: Alexintosh

I found I liked programming for the same reasons I liked to build models
::: CodeWisdom

1. Bitcoin will crash…again
::: jdegoes

Debugging a memory leak
::: MiriaGrunick

Whenever I try make a philosophical argument
::: EgriNagy

Is there a word for the almost immeasurably tiny feeling of satisfaction
::: neilhimself

Compile time error vs runtime error
::: amazedcoder

Ballerina’s movements mesmerizingly traced by algorithmically-generated geometries
::: scienmag

Capire i #bitcoin è molto più importante del loro valore
::: SergioGridelli

every time I have to interact with a python program
::: aphyr

The more you add to your software specific solutions to deal with corner cases
::: mariofusco

Google, define Cabal
::: TaurineAndCode

More interesting may be that each iteration (Atari, AlphaGo, AlphaGo Zero, AlphaZero) took dramatically less time to develop than the previous one
::: Plinz

I wonder if the Haskell people would pay for something that builds their projects 10x faster
::: TaurineAndCode

I’d really love to use Haskell more for my own tooling and scripting, but whenever I try I get stuck at
::: lunaryorn

This is the smaller point — everyone puts down textbooks and how-tos. But good textbooks do actually change people’s lives. Explaining things in print is not glamorous work, but is the great equalizer for many
::: holden

My 7 year old has been asking a lot of questions this Christmas season
::: Elizasoul80

Education appears to be the most consistent, robust, and durable method yet to be identified for raising intelligence
::: Noahpinion

A day in the life of a software engineer
::: laura_nobilis

The cat stack is an important data structure every purrgrammer should know and understand
::: laura_nobilis

Stupid tech problems
::: hacks4pancakes

The bitcoin bubble will not burst as long as so many critics call it a bubble
::: marcelsalathe

Significato ontologico? Qui la mia professoressa di italiano non avrebbe avuto dubbi!
::: LauraBignami1

programmers: names and cache coherence
::: tef_ebooks

(Bug)Fixing car using …
::: ismonkeyuser

In carpentry, you measure twice and cut once
::: CodeWisdom

Apple went public #otd in 1980
::: MIT_CSAIL

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

No you don’t understand, blockchain technology means this will be the first speculative bubble for which we have a full transaction ledger
::: WAWilsonIV

Simple doesn’t mean stupid
::: CodeWisdom

The Go Programming Language literally exists because Google
::: bhurt42

There is nothing more unproductive than to build something efficiently
::: CodeWisdom

The role of software architect…
::: RichRogersIoT

Don’t worry about what anyone else is going to do
::: CodeWisdom

Haskell – 61 – sintassi nelle funzioni – 1

Continuo da qui, copio qui.

Pattern matching
No, non so come tradurlo, ho carenze linguistiche 😐

This chapter will cover some of Haskell’s cool syntactic constructs and we’ll start with pattern matching. Pattern matching consists of specifying patterns to which some data should conform and then checking to see if it does and deconstructing the data according to those patterns.

When defining functions, you can define separate function bodies for different patterns. This leads to really neat code that’s simple and readable. You can pattern match on any data type — numbers, characters, lists, tuples, etc. Let’s make a really trivial function that checks if the number we supplied to it is a seven or not.

lucky.hs

lucky :: (Integral a) => a -> String
lucky 7 = "LUCKY NUMBER SEVEN!"
lucky x = "Sorry, you're out of luck, pal!"
Prelude> :l lucky
[1 of 1] Compiling Main             ( lucky.hs, interpreted )
Ok, modules loaded: Main.
*Main> lucky 5
"Sorry, you're out of luck, pal!"
*Main> lucky 7
"LUCKY NUMBER SEVEN!"

When you call lucky, the patterns will be checked from top to bottom and when it conforms to a pattern, the corresponding function body will be used. The only way a number can conform to the first pattern here is if it is 7. If it’s not, it falls through to the second pattern, which matches anything and binds it to x. This function could have also been implemented by using an if statement. But what if we wanted a function that says the numbers from 1 to 5 and says “Not between 1 and 5” for any other number? Without pattern matching, we’d have to make a pretty convoluted if then else tree. However, with it:

sayMe.hs

sayMe :: (Integral a) => a -> String
sayMe 1 = "One!"
sayMe 2 = "Two!"
sayMe 3 = "Three!"
sayMe 4 = "Four!"
sayMe 5 = "Five!"
sayMe x = "Not between 1 and 5"
*Main> :l sayMe
[1 of 1] Compiling Main             ( sayMe.hs, interpreted )
Ok, modules loaded: Main.
*Main> sayMe 3
"Three!"
*Main> sayMe 8
"Not between 1 and 5"

Note that if we moved the last pattern (the catch-all one) to the top, it would always say “Not between 1 and 5”, because it would catch all the numbers and they wouldn’t have a chance to fall through and be checked for any other patterns.

Remember the factorial function we implemented previously? We defined the factorial of a number n as product [1..n]. We can also define a factorial function recursively, the way it is usually defined in mathematics. We start by saying that the factorial of 0 is 1. Then we state that the factorial of any positive integer is that integer multiplied by the factorial of its predecessor. Here’s how that looks like translated in Haskell terms.

fact.hs

factorial :: (Integral a) => a -> a
factorial 0 = 1
factorial n = n * factorial (n - 1)
*Main> :l fact
[1 of 1] Compiling Main             ( fact.hs, interpreted )
Ok, modules loaded: Main.
*Main> factorial 5
120
*Main> factorial 12
479001600

This is the first time we’ve defined a function recursively. Recursion is important in Haskell and we’ll take a closer look at it later. But in a nutshell, this is what happens if we try to get the factorial of, say, 3. It tries to compute 3 * factorial 2. The factorial of 2 is 2 * factorial 1, so for now we have 3 * (2 * factorial 1). factorial 1 is 1 * factorial 0, so we have 3 * (2 * (1 * factorial 0)). Now here comes the trick — we’ve defined the factorial of 0 to be just 1 and because it encounters that pattern before the catch-all one, it just returns 1. So the final result is equivalent to 3 * (2 * (1 * 1)). Had we written the second pattern on top of the first one, it would catch all numbers, including 0 and our calculation would never terminate. That’s why order is important when specifying patterns and it’s always best to specify the most specific ones first and then the more general ones later.

Pattern matching can also fail. If we define a function like this:

charName.hs

charName :: Char -> String
charName 'a' = "Alice"
charName 'b' = "Bob"
charName 'c' = "Charlie"

and then try to call it with an input that we didn’t expect, this is what happens:

*Main> :l charName
[1 of 1] Compiling Main             ( charName.hs, interpreted )
Ok, modules loaded: Main.
*Main> charName 'b'
"Bob"
*Main> charName 'a'
"Alice"
*Main> charName 'c'
"Charlie"
*Main> charName 'd'
"*** Exception: charName.hs:(2,1)-(4,24): Non-exhaustive patterns in function charName

It complains that we have non-exhaustive patterns, and rightfully so. When making patterns, we should always include a catch-all pattern so that our program doesn’t crash if we get some unexpected input.

Pattern matching can also be used on tuples. What if we wanted to make a function that takes two vectors in a 2D space (that are in the form of pairs) and adds them together? To add together two vectors, we add their x components separately and then their y components separately. Here’s how we would have done it if we didn’t know about pattern matching:

addVecs.hs

addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a)
addVectors a b = (fst a + fst b, snd a + snd b)
*Main> :l addVecs
[1 of 1] Compiling Main             ( addVecs.hs, interpreted )
Ok, modules loaded: Main.
*Main> addVectors (1, 2) (3, 4)
(4,6)

Well, that works, but there’s a better way to do it. Let’s modify the function so that it uses pattern matching.

addVecs-pm.hs

addVectors' :: (Num a) => (a, a) -> (a, a) -> (a, a)
addVectors' (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
*Main> :l addVecs-pm
[1 of 1] Compiling Main             ( addVecs-pm.hs, interpreted )
Ok, modules loaded: Main.
*Main> addVectors' (1, 2) (3, 4)
(4,6)

There we go! Much better. Note that this is already a catch-all pattern. The type of addVectors (in both cases) is addVectors :: (Num a) => (a, a) -> (a, a) - > (a, a), so we are guaranteed to get two pairs as parameters.

fst and snd extract the components of pairs. But what about triples? Well, there are no provided functions that do that but we can make our own.

fst.hs

first :: (a, b, c) -> a
first (x, _, _) = x

second :: (a, b, c) -> b
second (_, y, _) = y

third :: (a, b, c) -> c
third (_, _, z) = z

The _ means the same thing as it does in list comprehensions. It means that we really don’t care what that part is, so we just write a _.

Which reminds me, you can also pattern match in list comprehensions. Check this out:

*Main> xs = [(1,3), (4,3), (2,4), (5,3), (5,6), (3,1)]
*Main> [a+b | (a,b) <- xs]
[4,7,6,8,11,4]

Should a pattern match fail, it will just move on to the next element.

Lists themselves can also be used in pattern matching. You can match with the empty list [] or any pattern that involves : and the empty list. But since [1,2,3] is just syntactic sugar for 1:2:3:[], you can also use the former pattern. A pattern like x:xs will bind the head of the list to x and the rest of it to xs, even if there’s only one element so xs ends up being an empty list.

Note: The x:xs pattern is used a lot, especially with recursive functions. But patterns that have : in them only match against lists of length 1 or more.

If you want to bind, say, the first three elements to variables and the rest of the list to another variable, you can use something like x:y:z:zs. It will only match against lists that have three elements or more.

Now that we know how to pattern match against list, let’s make our own implementation of the head function.

myHead.hs

head' :: [a] -> a
head' [] = error "Can't call head on an empty list, dummy!"
head' (x:_) = x

Checking if it works:

*Main> :l myHead
[1 of 1] Compiling Main             ( myHead.hs, interpreted )
Ok, modules loaded: Main.
*Main> head' [4,5,6]
4
*Main> head' "Hello"
'H'

Nice! Notice that if you want to bind to several variables (even if one of them is just _ and doesn’t actually bind at all), we have to surround them in parentheses. Also notice the error function that we used. It takes a string and generates a runtime error, using that string as information about what kind of error occurred. It causes the program to crash, so it’s not good to use it too much. But calling head on an empty list doesn’t make sense.

Let’s make a trivial function that tells us some of the first elements of the list in (in)convenient English form.

tell.hs

tell :: (Show a) => [a] -> String
tell [] = "The list is empty"
tell (x:[]) = "The list has one element: " ++ show x
tell (x:y:[]) = "The list has two elements: " ++ show x ++ " and " ++ show y
tell (x:y:_) = "This list is long. The first two elements are: " ++ show x ++ " and " ++ show y
*Main> :l tell
[1 of 1] Compiling Main             ( tell.hs, interpreted )
Ok, modules loaded: Main.
*Main> tell ""
"The list is empty"
*Main> tell "ciao"
"This list is long. The first two elements are: 'c' and 'i'"
*Main> tell ("ciao")
"This list is long. The first two elements are: 'c' and 'i'"
*Main> tell ["ciao"]
"The list has one element: \"ciao\""

This function is safe because it takes care of the empty list, a singleton list, a list with two elements and a list with more than two elements. Note that (x:[]) and (x:y:[]) could be rewriten as [x] and [x,y] (because its syntatic sugar, we don’t need the parentheses). We can’t rewrite (x:y:_) with square brackets because it matches any list of length 2 or more.

We already implemented our own length function using list comprehension. Now we’ll do it by using pattern matching and a little recursion:

len.hs

length' :: (Num b) => [a] -> b
length' [] = 0
length' (_:xs) = 1 + length' xs
*Main> :l len
[1 of 1] Compiling Main             ( len.hs, interpreted )
Ok, modules loaded: Main.
*Main> length' ""
0
*Main> length' "ciao Juhan!"
11
*Main> length' [1,2,3]
3

This is similar to the factorial function we wrote earlier. First we defined the result of a known input — the empty list. This is also known as the edge condition. Then in the second pattern we take the list apart by splitting it into a head and a tail. We say that the length is equal to 1 plus the length of the tail. We use _ to match the head because we don’t actually care what it is. Also note that we’ve taken care of all possible patterns of a list. The first pattern matches an empty list and the second one matches anything that isn’t an empty list.

Let’s see what happens if we call length' on "ham". First, it will check if it’s an empty list. Because it isn’t, it falls through to the second pattern. It matches on the second pattern and there it says that the length is 1 + length' "am", because we broke it into a head and a tail and discarded the head. O-kay. The length' of "am" is, similarly, 1 + length' "m". So right now we have 1 + (1 + length' "m"). length' "m" is 1 + length' "" (could also be written as 1 + length' []). And we’ve defined length' [] to be 0. So in the end we have 1 + (1 + (1 + 0)).

Let’s implement sum. We know that the sum of an empty list is 0. We write that down as a pattern. And we also know that the sum of a list is the head plus the sum of the rest of the list. So if we write that down, we get:

mySum.hs

sum' :: (Num a) => [a] -> a
sum' [] = 0
sum' (x:xs) = x + sum' xs
*Main> :l mySum
[1 of 1] Compiling Main             ( mySum.hs, interpreted )
Ok, modules loaded: Main.
*Main> sum' []
0
*Main> sum' [1,2,3]
6

There’s also a thing called as patterns. Those are a handy way of breaking something up according to a pattern and binding it to names whilst still keeping a reference to the whole thing. You do that by putting a name and an @ in front of a pattern. For instance, the pattern xs@(x:y:ys). This pattern will match exactly the same thing as x:y:ys but you can easily get the whole list via xs instead of repeating yourself by typing out x:y:ys in the function body again. Here’s a quick and dirty example:

cap.hs

capital :: String -> String
capital "" = "Empty string, whoops!"
capital all@(x:xs) = "The first letter of " ++ all ++ " is " ++ [x]
*Main> :l cap
[1 of 1] Compiling Main             ( cap.hs, interpreted )
Ok, modules loaded: Main.
*Main> capital ""
"Empty string, whoops!"
*Main> capital "Juhan"
"The first letter of Juhan is J"

Normally we use as patterns to avoid repeating ourselves when matching against a bigger pattern when we have to use the whole thing again in the function body. NOn mi è tanto chiaro quando convenga; da approfondire.

One more thing — you can’t use ++ in pattern matches. If you tried to pattern match against (xs ++ ys), what would be in the first and what would be in the second list? It doesn’t make much sense. It would make sense to match stuff against (xs ++ [x,y,z]) or just (xs ++ [x]), but because of the nature of lists, you can’t do that.

🤩

Haskell – 60 – tipi e classi di tipi – 2

Continuo da qui, copio qui.

Tipi variabili
What do you think is the type of the head function? Because head takes a list of any type and returns the first element, so what could it be? Let’s check!

Prelude> :t head
head :: [a] -> a

Hmmm! What is this a? Is it a type? Remember that we previously stated that types are written in capital case, so it can’t exactly be a type. Because it’s not in capital case it’s actually a type variable. That means that a can be of any type. This is much like generics in other languages, only in Haskell it’s much more powerful because it allows us to easily write very general functions if they don’t use any specific behavior of the types in them. Functions that have type variables are called polymorphic functions. The type declaration of head states that it takes a list of any type and returns one element of that type.

Although type variables can have names longer than one character, we usually give them names of a, b, c, d, ....

Remember fst? It returns the first component of a pair. Let’s examine its type.

Prelude> :t fst
fst :: (a, b) -> a

We see that fst takes a tuple which contains two types and returns an element which is of the same type as the pair’s first component. That’s why we can use fst on a pair that contains any two types. Note that just because a and b are different type variables, they don’t have to be different types. It just states that the first component’s type and the return value’s type are the same.

Typeclasses 101
A typeclass is a sort of interface that defines some behavior. If a type is a part of a typeclass, that means that it supports and implements the behavior the typeclass describes. A lot of people coming from OOP get confused by typeclasses because they think they are like classes in object oriented languages. Well, they’re not. You can think of them kind of as Java interfaces, only better.

What’s the type signature of the == function?

Prelude> :t (==)
(==) :: Eq a => a -> a -> Bool

Note: the equality operator, == is a function. So are +, *, -, / and pretty much all operators. If a function is comprised only of special characters, it’s considered an infix function by default. If we want to examine its type, pass it to another function or call it as a prefix function, we have to surround it in parentheses.

Interesting. We see a new thing here, the => symbol. Everything before the => symbol is called a class constraint. We can read the previous type declaration like this: the equality function takes any two values that are of the same type and returns a Bool. The type of those two values must be a member of the Eq class (this was the class constraint).

The Eq typeclass provides an interface for testing for equality. Any type where it makes sense to test for equality between two values of that type should be a member of the Eq class. All standard Haskell types except for IO (the type for dealing with input and output) and functions are a part of the Eq typeclass.

The elem function has a type of (Eq a) => a -> [a] -> Bool because it uses == over a list to check whether some value we’re looking for is in it.

Some basic typeclasses:

Eq is used for types that support equality testing. The functions its members implement are == and /=. So if there’s an Eq class constraint for a type variable in a function, it uses == or /= somewhere inside its definition. All the types we mentioned previously except for functions are part of Eq, so they can be tested for equality.

Prelude> 5 == 5
True
Prelude> 5 /= 5
False
Prelude> 'a' == 'a'
True
Prelude> "Ho Ho" == "Ho Ho"
True
Prelude> 3.432 == 3.432
True

Ord is for types that have an ordering.

Prelude> :t (>)
(>) :: Ord a => a -> a -> Bool

All the types we covered so far except for functions are part of Ord. Ord covers all the standard comparing functions such as >, <, >= and <=. The compare function takes two Ord members of the same type and returns an ordering. Ordering is a type that can be GT, LT or EQ, meaning greater than, lesser than and equal, respectively.

To be a member of Ord, a type must first have membership in the prestigious and exclusive Eq club.

Prelude> "Abrakadabra" `compare` "Zebra"
LT
Prelude> 5 >= 2
True
Prelude> 5 `compare` 3
GT

Members of Show can be presented as strings. All types covered so far except for functions are a part of Show. The most used function that deals with the Show typeclass is show. It takes a value whose type is a member of Show and presents it to us as a string.

Prelude> show 3
"3"
Prelude> show 3.1415
"3.1415"
Prelude> show True
"True"

Read is sort of the opposite typeclass of Show. The read function takes a string and returns a type which is a member of Read.

Prelude> read "True" || False
True
Prelude> read "8.2" + 3.8
12.0
Prelude> read "5" - 2
3
Prelude> read "[1,2,3,4]" ++ [3]
[1,2,3,4,3]

So far so good. Again, all types covered so far are in this typeclass. But what happens if we try to do just read "4"?

Prelude> read "4"
*** Exception: Prelude.read: no parse

A Miran, che usa una versione precedente di GHC, da un messaggio più esteso:

Prelude> read "4"
:1:0:
    Ambiguous type variable `a' in the constraint:
      `Read a' arising from a use of `read' at :1:0-7
    Probable fix: add a type signature that fixes these type variable(s)

What GHCI is telling us here is that it doesn’t know what we want in return. Notice that in the previous uses of read we did something with the result afterwards. That way, GHCI could infer what kind of result we wanted out of our read. If we used it as a boolean, it knew it had to return a Bool. But now, it knows we want some type that is part of the Read class, it just doesn’t know which one. Let’s take a look at the type signature of read.

Prelude> :t read
read :: Read a => String -> a

See? It returns a type that’s part of Read but if we don’t try to use it in some way later, it has no way of knowing which type. That’s why we can use explicit type annotations. Type annotations are a way of explicitly saying what the type of an expression should be. We do that by adding :: at the end of the expression and then specifying a type. Observe:

Prelude> read "5" :: Int
5
Prelude> read "5" :: Float
5.0
Prelude> (read "5" :: Float) * 4
20.0
Prelude> read "[1,2,3,4]" :: [Int]
[1,2,3,4]
Prelude> read "(3, 'a')" :: (Int, Char)
(3,'a')

Most expressions are such that the compiler can infer what their type is by itself. But sometimes, the compiler doesn’t know whether to return a value of type Int or Float for an expression like read "5". To see what the type is, Haskell would have to actually evaluate read "5". But since Haskell is a statically typed language, it has to know all the types before the code is compiled (or in the case of GHCI, evaluated). So we have to tell Haskell: “Hey, this expression should have this type, in case you don’t know!”.

Enum members are sequentially ordered types — they can be enumerated. The main advantage of the Enum typeclass is that we can use its types in list ranges. They also have defined successors and predecesors, which you can get with the succ and pred functions. Types in this class: (), Bool, Char, Ordering, Int, Integer, Float and Double.

Prelude> ['a'..'e']
"abcde"
Prelude> [LT .. GT]
[LT,EQ,GT]
Prelude> [3 .. 5]
[3,4,5]
Prelude> succ 'B'
'C'

Bounded members have an upper and a lower bound.

Prelude> minBound :: Int
-9223372036854775808
Prelude> maxBound :: Char
'\1114111'
Prelude> maxBound :: Bool
True
Prelude> minBound :: Bool
False

minBound and maxBound are interesting because they have a type of (Bounded a) => a. In a sense they are polymorphic constants.

All tuples are also part of Bounded if the components are also in it.

Prelude> maxBound :: (Bool, Int, Char)
(True,9223372036854775807,'\1114111')

Num is a numeric typeclass. Its members have the property of being able to act like numbers. Let’s examine the type of a number.

Prelude> :t 20
20 :: Num t => t

It appears that whole numbers are also polymorphic constants. They can act like any type that’s a member of the Num typeclass.

Prelude> 20 :: Int
20
Prelude> 20 :: Integer
20
Prelude> 20 :: Float
20.0
Prelude> 20 :: Double
20.0

Those are types that are in the Num typeclass. If we examine the type of *, we’ll see that it accepts all numbers.

Prelude> :t (*)
(*) :: Num a => a -> a -> a

It takes two numbers of the same type and returns a number of that type. That’s why (5 :: Int) * (6 :: Integer) will result in a type error whereas 5 * (6 :: Integer) will work just fine and produce an Integer because 5 can act like an Integer or an Int.

To join Num, a type must already be friends with Show and Eq.

Integral is also a numeric typeclass. Num includes all numbers, including real numbers and integral numbers, Integral includes only integral (whole) numbers. In this typeclass are Int and Integer.

Floating includes only floating point numbers, so Float and Double.

A very useful function for dealing with numbers is fromIntegral. It has a type declaration of fromIntegral :: (Num b, Integral a) => a -> b. From its type signature we see that it takes an integral number and turns it into a more general number. That’s useful when you want integral and floating point types to work together nicely. For instance, the length function has a type declaration of length :: [a] -> Int instead of having a more general type of (Num b) => length :: [a] -> b. I think that’s there for historical reasons or something, although in my opinion, it’s pretty stupid. Anyway, if we try to get a length of a list and then add it to 3.2, we’ll get an error because we tried to add together an Int and a floating point number. So to get around this, we do fromIntegral (length [1,2,3,4]) + 3.2 and it all works out.

Notice that fromIntegral has several class constraints in its type signature. That’s completely valid and as you can see, the class constraints are separated by commas inside the parentheses.

🤩

Caos informativo

Un post –uno sfogo– un po’ diverso dal solito, su un argomento diverso dal solito ma che è importante, secondo me.

Per introdurlo ecco Valigia Blu (la conoscete e seguite vero? dovreste e dovreste sostenerla), questo: Un anno di f**e news: il lavoro di Valigia Blu sul caos informativo.

Io che sono twitter-centrico ce l’ho qui. Ci sono arrivato via Fabio Chiusi. Fabio me l’ha fatto conoscere JuanCarlos De Martin di Nexa.

OK, basta consigli dalla regia, ma quando {ci vuole}*2 😁

Non so se è una considerazione solo mia ma riesco a sopportare (e spesso a evitare) le fakes nel Web. Basta fare attenzione a quelli con cui si interagisce nei social-cosi. Per esempio su Facebook (seguo distrattamente, spesso semi-trollando (o trollando proprio)) devi confermare l’amicizia e basta dire di no, anzi basta non confermare, non dire niente. Google Plus lo visito ancora meno, anche se è più interessante. Invece sono assiduo su Twitter dove seguo 220-230 (numero soggetto a variazioni umorali) cinguettatori. Dovrebbero essere molti di più ma non avrei il tempo per leggere i loro tweets, spesso accompagnati da collegamenti, spesso impegnativi. Inoltre la stragrante maggioranza di loro parlano di ‘puters, di programmazione, quella che non ho finora potuto usare, ma non voglio perdermi, voi giovani se non lo fate ora lo farete presto. Probabilmente… Forse… 😐

Lì una cosa interessante sono i retweets, trovi gente nuova (anche troppi come dicevo) e spesso impulsivamente schiacci Segui (e poi cerchi di controbilanciare scancellando qualcuno). Per me valgono anche le raccomandazioni negative: uno che retwitta Giuliano Ferrara o Oscar Giannino o Gianni Riotta viene scancellato prima di subito. Invece si può citare Paolo Brosio, senza timore. Questione di gusti personali.

So di non influire per niente (nada, zilch) per cui non vado a caccia (anzi li evito) i gomblottisti, gli anti-vaxers, e simili.

Diversa la situazione alla tele. Anche perché non sono quello con il telecomando. E le rare volte che sento le notizie devo sentire come sottofondo (avete presente le usanze dei padagni?) i commenti a tutto tranne i disastri e incidenti stradali locali (solo locali, poi se si conosce qualcuno personalmente meglio, assay). Ma di solito sono Vita in Diretta e Punta il Dito, i Pakki non li fanno più.

E c’è il #cazzaro. Quando c’era Lui (il Silvio) era scandaloso come la tele riusciva a essere parziale senza vergogna. Adesso è peggiorata.

La stampa di carta (escluse poche eccezioni) è simile. Non so se avete presente la banda dell’Eugenio (il font)? Insomma fakes dappertutto, travolgenti.

Come esercizio di esorcizzamento ho realizzato che se pubblico un elenco di esempi (freschi di giornata) poi mi sento più tranquillo, come ho già fatto e visto con il Bitcoin. Non mi aspetto risultati, solo sentirmi a posto, un po’ più vicino al nirvana, smarcato dalla folla –come dire– comprendonialmente svantaggiata.

Mi accorgo adesso che la selezione è parziale, poche fonti, ripetute. Ma l’argomento mi provoca sconvolgimenti intestinali, non insisto. Se volete potete farlo da voi, è –purtroppo– molto facile.

Per intanto faccio mio l’appello di Claire Wardle e di Valigia Blu, userò caos informativo (information disorder) al posto di fakes news.

🤩

Haskell – 59 – tipi e classi di tipi – 1

Continuo da qui, copio qui.

Previously we mentioned that Haskell has a static type system. The type of every expression is known at compile time, which leads to safer code. If you write a program where you try to divide a boolean type with some number, it won’t even compile. That’s good because it’s better to catch such errors at compile time instead of having your program crash. Everything in Haskell has a type, so the compiler can reason quite a lot about your program before compiling it.

Unlike Java or Pascal, Haskell has type inference. If we write a number, we don’t have to tell Haskell it’s a number. It can infer that on its own, so we don’t have to explicitly write out the types of our functions and expressions to get things done. We covered some of the basics of Haskell with only a very superficial glance at types. However, understanding the type system is a very important part of learning Haskell.

A type is a kind of label that every expression has. It tells us in which category of things that expression fits. The expression True is a boolean, "hello" is a string, etc.

Now we’ll use GHCI to examine the types of some expressions. We’ll do that by using the :t command which, followed by any valid expression, tells us its type. Let’s give it a whirl.

Prelude> :t 'a'
'a' :: Char
Prelude> :t True
True :: Bool
Prelude> :t "HELLO!"
"HELLO!" :: [Char]
Prelude> :t (True, 'a')
(True, 'a') :: (Bool, Char)
Prelude> :t 4 == 5
4 == 5 :: Bool

Here we see that doing :t on an expression prints out the expression followed by :: and its type. :: is read as “has type of“. Explicit types are always denoted with the first letter in capital case. 'a', as it would seem, has a type of Char. It’s not hard to conclude that it stands for character. True is of a Bool type. That makes sense. But what’s this? Examining the type of "HELLO!" yields a [Char]. The square brackets denote a list. So we read that as it being a list of characters. Unlike lists, each tuple length has its own type. So the expression of (True, 'a') has a type of (Bool, Char), whereas an expression such as ('a','b','c') would have the type of (Char, Char, Char). 4 == 5 will always return False, so its type is Bool.

Functions also have types. When writing our own functions, we can choose to give them an explicit type declaration. This is generally considered to be good practice except when writing very short functions. From here on, we’ll give all the functions that we make type declarations. Remember the list comprehension we made previously that filters a string so that only caps remain? Here’s how it looks like with a type declaration.

removeNonUppercase :: [Char] -> [Char]
removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']]

removeNonUppercase has a type of [Char] -> [Char], meaning that it maps from a string to a string. That’s because it takes one string as a parameter and returns another as a result. The [Char] type is synonymous with String so it’s clearer if we write removeNonUppercase :: String -> String. We didn’t have to give this function a type declaration because the compiler can infer by itself that it’s a function from a string to a string but we did anyway. But how do we write out the type of a function that takes several parameters? Here’s a simple function that takes three integers and adds them together:

addThree :: Int -> Int -> Int -> Int
addThree x y z = x + y + z

The parameters are separated with -> and there’s no special distinction between the parameters and the return type. The return type is the last item in the declaration and the parameters are the first three. Later on we’ll see why they’re all just separated with -> instead of having some more explicit distinction between the return types and the parameters like Int, Int, Int -> Int or something.

If you want to give your function a type declaration but are unsure as to what it should be, you can always just write the function without it and then check it with :t. Functions are expressions too, so :t works on them without a problem.

Nota: prima di continuare voglio aggiungere una cosa che Miran non dice (almeno non qui). Nella REPL di GHC non è possibile dichuarare i tipi, almeno non direttamente. Ma è semplicissimo (e spesso consigliabile) ricorrere a scrivere il codice in un file e caricarlo con :l (o :load). Per esempio la sunfiona addThree la metto nel file add3.hs:

add3.hs

addThree :: Int -> Int -> Int -> Int
addThree x y z = x + y + z
Prelude> :l add3
[1 of 1] Compiling Main             ( add3.hs, interpreted )
Ok, modules loaded: Main.
*Main> addThree 1 2 3
6
*Main> addThree 11 12 13
36

Here’s an overview of some common types.

Int stands for integer. It’s used for whole numbers. 7 can be an Int but 7.2 cannot. Int is bounded, which means that it has a minimum and a maximum value. Usually on 32-bit machines the maximum possible Int is 2147483647, (2^31 – 1) and the minimum is -2147483648.

Integer stands for, er … also integer. The main difference is that it’s not bounded so it can be used to represent really really big numbers. I mean like really big. Int, however, is more efficient.

fact.hs

factorial :: Integer -> Integer
factorial n = product [1..n]
*Main> :l fact
[1 of 1] Compiling Main             ( fact.hs, interpreted )
Ok, modules loaded: Main.
*Main> factorial 50
30414093201713378043612608166064768844377641568960512000000000000

Float is a real floating point with single precision.

circ-sp.hs

circumference :: Float -> Float
circumference r = 2 * pi * r
*Main> :l circ-sp
[1 of 1] Compiling Main             ( circ-sp.hs, interpreted )
Ok, modules loaded: Main.
*Main> circumference 4.0
25.132742
*Main> circumference 4
25.132742

Double is a real floating point with double the precision.

circ.dp.hs

circumference' :: Double -> Double
circumference' r = 2 * pi * r
*Main> :l circ-dp
[1 of 1] Compiling Main             ( circ-dp.hs, interpreted )
Ok, modules loaded: Main.
*Main> circumference' 4.0
25.132741228718345
*Main> circumference' 4
25.132741228718345

Bool is a boolean type. It can have only two values: True and False.

Char represents a character. It’s denoted by single quotes. A list of characters is a string.

Tuples are types but they are dependent on their length as well as the types of their components, so there is theoretically an infinite number of tuple types, which is too many to cover in this tutorial. Note that the empty tuple () is also a type which can only have a single value: ().

🤩

Haskell – 58 – inizio – 6

Continuo da qui, copio qui.

Tuple
In some ways, tuples are like lists — they are a way to store several values into a single value. However, there are a few fundamental differences. A list of numbers is a list of numbers. That’s its type and it doesn’t matter if it has only one number in it or an infinite amount of numbers. Tuples, however, are used when you know exactly how many values you want to combine and its type depends on how many components it has and the types of the components. They are denoted with parentheses and their components are separated by commas.

Another key difference is that they don’t have to be homogenous. Unlike a list, a tuple can contain a combination of several types.

Think about how we’d represent a two-dimensional vector in Haskell. One way would be to use a list. That would kind of work. So what if we wanted to put a couple of vectors in a list to represent points of a shape on a two-dimensional plane? We could do something like [[1,2],[8,11],[4,5]]. The problem with that method is that we could also do stuff like [[1,2],[8,11,5],[4,5]], which Haskell has no problem with since it’s still a list of lists with numbers but it kind of doesn’t make sense. But a tuple of size two (also called a pair) is its own type, which means that a list can’t have a couple of pairs in it and then a triple (a tuple of size three), so let’s use that instead. Instead of surrounding the vectors with square brackets, we use parentheses: [(1,2),(8,11),(4,5)]. What if we tried to make a shape like [(1,2),(8,11,5),(4,5)]? Well, we’d get this error:

Prelude> t = [[1,2],[8,11],[4,5]]
Prelude> t' = [[1,2],[8,11,5],[4,5]]
Prelude> u = [(1,2),(8,11),(4,5)]
Prelude> u' = [(1,2),(8,11,5),(4,5)]

:4:13: error:
    • Couldn't match expected type ‘(t1, t)’
                  with actual type ‘(Integer, Integer, Integer)’
    • In the expression: (8, 11, 5)
      In the expression: [(1, 2), (8, 11, 5), (4, 5)]
      In an equation for ‘u'’: u' = [(1, 2), (8, 11, 5), (4, 5)]
    • Relevant bindings include
        u' :: [(t1, t)] (bound at :4:1)

It’s telling us that we tried to use a pair and a triple in the same list, which is not supposed to happen. You also couldn’t make a list like [(1,2),("One",2)] because the first element of the list is a pair of numbers and the second element is a pair consisting of a string and a number. Tuples can also be used to represent a wide variety of data. For instance, if we wanted to represent someone’s name and age in Haskell, we could use a triple: ("Christopher", "Walken", 55). As seen in this example, tuples can also contain lists.

Use tuples when you know in advance how many components some piece of data should have. Tuples are much more rigid because each different size of tuple is its own type, so you can’t write a general function to append an element to a tuple — you’d have to write a function for appending to a pair, one function for appending to a triple, one function for appending to a 4-tuple, etc.

While there are singleton lists, there’s no such thing as a singleton tuple. It doesn’t really make much sense when you think about it. A singleton tuple would just be the value it contains and as such would have no benefit to us.

Like lists, tuples can be compared with each other if their components can be compared. Only you can’t compare two tuples of different sizes, whereas you can compare two lists of different sizes. Two useful functions that operate on pairs:

fst takes a pair and returns its first component.

Prelude> fst (8,11)
8
Prelude> fst ("Wow", False)
"Wow"

snd takes a pair and returns its second component. Surprise!

Prelude> snd (8,11)
11
Prelude> snd ("Wow", False)
False

Note: these functions operate only on pairs. They won’t work on triples, 4-tuples, 5-tuples, etc. We’ll go over extracting data from tuples in different ways a bit later.

A cool function that produces a list of pairs: zip. It takes two lists and then zips them together into one list by joining the matching elements into pairs. It’s a really simple function but it has loads of uses. It’s especially useful for when you want to combine two lists in a way or traverse two lists simultaneously. Here’s a demonstration.

Prelude>  zip [1,2,3,4,5] [5,5,5,5,5]
[(1,5),(2,5),(3,5),(4,5),(5,5)]
Prelude> zip [1 .. 5] ["one", "two", "three", "four", "five"]
[(1,"one"),(2,"two"),(3,"three"),(4,"four"),(5,"five")]

It pairs up the elements and produces a new list. The first element goes with the first, the second with the second, etc. Notice that because pairs can have different types in them, zip can take two lists that contain different types and zip them up. What happens if the lengths of the lists don’t match?

Prelude> zip [5,3,2,6,2,7,2,5,4,6,6] ["im","a","turtle"]
[(5,"im"),(3,"a"),(2,"turtle")]

The longer list simply gets cut off to match the length of the shorter one. Because Haskell is lazy, we can zip finite lists with infinite lists:

Prelude> zip [1..] ["apple", "orange", "cherry", "mango"]
[(1,"apple"),(2,"orange"),(3,"cherry"),(4,"mango")]

Here’s a problem that combines tuples and list comprehensions: which right triangle that has integers for all sides and all sides equal to or smaller than 10 has a perimeter of 24? First, let’s try generating all triangles with sides equal to or smaller than 10:

Prelude> triangles = [ (a,b,c) | c <- [1..10], b <- [1..10], a <- [1..10] ]

We’re just drawing from three lists and our output function is combining them into a triple. If you evaluate that by typing out triangles in GHCI, you’ll get a list of all possible triangles with sides under or equal to 10. Next, we’ll add a condition that they all have to be right triangles. We’ll also modify this function by taking into consideration that side b isn’t larger than the hypothenuse and that side a isn’t larger than side b.

Prelude> rightTriangles = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2]

We’re almost done. Now, we just modify the function by saying that we want the ones where the perimeter is 24.

Prelude> rightTriangles' = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c == 24] 
Prelude> rightTriangles'
[(6,8,10)]

And there’s our answer! This is a common pattern in functional programming. You take a starting set of solutions and then you apply transformations to those solutions and filter them until you get the right ones.

🤩

Visto nel Web – 317

Gingu beh, gingu beh  no, ancora troppo presto, ancora stagione di fakes (quelle del #cazzaro, ma non solo). Intanto ecco cosa ho wisto nel Web.

Perl, Perl 6, and Two Application Frameworks Release 2017 Advent Calendars
#:linguaggi di programmazione
::: Slashdot

No laptop in the lecture hall or no lecture hall? As tech evolves, education should too.
#:scuola, educazione
::: NicoSchuele ::: verge

Extending Unix Pipelines to DAGs
#:programming, codice, snippet
::: b3h3m0th

Mozilla Releases Open Source Speech Recognition Model, Massive Voice Dataset
#:free open source software
::: Slashdot

Improving Function Coverage with Munch: A Hybrid Fuzzing and Directed Symbolic Execution Approach
#:programming, codice, snippet
::: johnregehr

And yet, a discussion about fake news on tv is nowhere to be found
#:fake news, bufale
::: fabiochiusi

Experts say technology alone can’t win the battle against misinformation online in the coming decade
#:fake news, bufale
::: pewinternet

Understanding the New Red Hat-IBM-Google-Facebook GPL Enforcement Announcement
#:free open source software
::: Slashdot

If you found the “Facebook emotion manipulation” paper disturbing, how would you feel about this paper which analyses the posts that you wrote on Facebook but eventually never sent, and naively assumed nobody is watching?
#:social media
::: TahaYasseri

Raspberry Pi A to Z
tanti tweets, racolgo
#:sistemi operativi
::: WTSxDEV ::: WTSxDEV ::: WTSxDEV ::: WTSxDEV ::: WTSxDEV ::: WTSxDEV ::: WTSxDEV ::: WTSxDEV ::: WTSxDEV

Valuable Republican Donor Database Breached — By Other Republicans
#:sicurezza, spionaggio, virus
::: Slashdot

Shouting ‘Pay Your Taxes’, Activists Occupy Apple Stores in France
#:economia
::: Slashdot

This is a really nice introduction to some of the concept of Pure FP, I really think we’re eventually going to embrace it
#:programmazione funzionale
::: volothamp

How Converting A C++ Game to JavaScript Gave Us WebAssembly
#:linguaggi di programmazione
::: Slashdot

blog post about taking a sabbatical to work on ruby profiling tools
Julia –rockz– attendo impaziente
#:programming, codice, snippet
::: b0rk ::: b0rk

Aggiornamento del desktop Unity in arrivo su Ubuntu 16.04 LTS
#:tools, componenti software
::: dcavedon

Massive Financial Aid Data Breach Proves Stanford Lied For Years To MBAs
#:sicurezza, spionaggio, virus
::: Slashdot

This is a good reason to HTTPS even your mundane non-secret sites, e.g. your blog, because many people *do* have malicious ISPs who may otherwise alter your page content
#:sicurezza, spionaggio, virus
::: chris__martin

AnimeX: Come vedere tutti gli anime su PC Linux Windows & Mac
#:tools, componenti software
::: OS)(SIDE

This is mandatory reading: a collection of postmortems of cryptocurrency companies that went out of business due to an attack
#:sicurezza, spionaggio, virus
::: dinodaizovi

Twitter suspended a journalist for 10 days for a 6-year-old tweet that potentially wasn’t against the rules at the time she wrote it
#:censura
::: jilliancyork

Is Open Source Innovation Now All About Vendor On-Ramps?
#:free open source software
::: Slashdot

I’ve completed “Spiral Memory” – Day 3 – Advent of Code 2017
tutta la serie, nèh!
#:linguaggi di programmazione
::: thek3nger

rate.sx source code is available
#:Web, Internet
::: igor_chubin

Blockchain Governance: Programming Our Future
#:sicurezza, spionaggio, virus
::: Micio1970

Apple-China collusion really hit home when a Wuzhen volunteer handed me his brand new iPhone and asked how he could download a VPN and read the WSJ
#:censura
::: Liz_in_Shanghai

Automating System Data Analysis Using R
#:linguaggi di programmazione
::: b3h3m0th

Nobel Prize-Winning Economist Says Bitcoin ‘Ought to be Outlawed’
#:economia
::: Slashdot

Dell Begins Offering Laptops With Intel’s ‘Management Engine’ Disabled
#:sistemi operativi
::: Slashdot

Google’s AI Built an AI that Outperforms Any Made By Humans
#:artificial intelligence
::: Slashdot

A new blog post: Reflecting on Haskell in 2017
#:programmazione funzionale
::: smdiehl

Web Assembly now supported across all browsers
#:linguaggi di programmazione
::: Donearm

Improve your Bash scripts with Argbash
chissà se serve davvero
#:linguaggi di programmazione
::: lucaciavatta

#Russia threatens to set up its ‘own internet’ with China, India and pals
#:Web, Internet
::: accessnow

Facebook Launches New Messenger App for Young Kids — What Could Possibly Go Wrong?
#:social media
::: Slashdot

This looks like an interesting & useful project – combining scikit-learn’s machine learning API with xarray’s data model
#:linguaggi di programmazione
::: jakevdp

#otd in 2004 two Google researchers published a CS paper on MapReduce, a key innovation for data analysis
#:algoritmi, codice
::: MIT_CSAIL

Haskell-Day Roma (2017-11-18)
bravi! 😁
#:programmazione funzionale
::: Haskell-ITA

Might be useful to some, a round-up of #NIPS2017 round-ups
#:programmazione funzionale
::: jjvincent

I wrote about a project called Civil, which is based on the idea that the future of media will be built using blockchains and cryptocurrencies
#:media #:innovazioni, futuro
::: mathewi

Apple, Google CEOs Bring Star Power as China Promotes Censorship
#:censura
::: Slashdot

Fascinating look at AI for the social good – who wins and who loses?
#:artificial intelligence
::: masonweintraub

Join us to fight for net neutrality: take action today!
#:Web, Internet
::: fsf

Evolution of : Gif without the GIF
#web
::: WebReflection

Point-free or die: tacit programming in Haskell and beyond
per quando sarò meno niubbo
#:programmazione funzionale
::: Jose_A_Alonso

Neutralità della rete, “ecco la nostra battaglia per liberare gli utenti italiani”
#:Web, Internet
::: AlessLongo

Waldo/Wally… “How to Find Wally with a Neural Network”
#:programming, codice, snippet
::: dataandme

I think it’s time to compile and promote a list of design programmes that teach ethical design and take a critical look at the dark design / decoration practiced by the likes of Facebook, Google, etc
#:Web, Internet
::: aral

Lead Developer of Popular Windows Application Classic Shell Is Quitting
#:tools, componenti software
::: Slashdot

FCC Won’t Delay Vote, Says Net Neutrality Supporters Are ‘Desperate’
#:Web, Internet
::: Slashdot

Public entities are refusing to disclose details about algorithms that guide important decisions
#:algoritmi, codice #:sicurezza, spionaggio, virus
::: FrankPasquale

What does it cost to purchase 1GB of broadband data in developing countries?
#:Web, Internet #:economia
::: webfoundation

Al via il Tavolo sulla disinformazione online promosso da Agcom
#:fake news, bufale
::: AntonioNicita

In addition, “YouTube is continuing to develop advanced machine-learning technology to automatically flag problematic content for removal”
#:Web, Internet
::: fabiochiusi

2017 was the year digital ad spending finally beat TV
#:economia
::: fabiochiusi

released a new guile last week; various compiler improvements result in a bootstrap that’s 3x as fast (or less slow)
#:lisp(s)
::: andywingo

The Mother of All Demos
#:protagonisti #:storia
::: PaniczGodek

Humanity is not that blackmirror-y dumb (yet), after all
#:Web, Internet
::: fabiochiusi

Introduzione ad Haskell
per chi preferisce i video
#:programmazione funzionale
::: You Tube

Dati sanitari alle multinazionali, senza consenso: passa la norma in Italia
#:dati, raccolta #:sicurezza, spionaggio, virus
::: SMaurizi ::: barbaracarfagna

The issue of preserving our digital present for the future in a whole different and more complicated perspective
#:storia
::: tedeschini

YouTube To Hire More Than 10,000 Content Moderators on Staff Next Year To Stop Its Child Exploitation Problem
#:Web, Internet
::: Slashdot

Donald Trump is buying Facebook ads to complain about the “Fake News Machine”
come da noi il #cazzaro
#:social media #:politica
::: JuliaAngwin

New post: Installing Python Packages from a Jupyter Notebook. It should be easy, but it isn’t… here’s why
fondamentale per tutti i pythonistas
#:programming, codice, snippet
::: jakevdp

bite me, C++
#:linguaggi di programmazione
::: johnregehr

Microsoft Debuts Windows 10 on ARM; Asus and HP Unveil Laptops With 20-Hour Battery Life, Gigabit LTE
#:sistemi operativi
::: Slashdot

Simplistic programming is underrated
#:programming, codice, snippet
::: Daniel Lemire

If you can afford the performance cost of a higher level language, it’s probabably worth it
#:linguaggi di programmazione
::: _wilfredh

New Google Deepmind paper. They beat the best chess and shogi programs. After training 24 hours, it beat Stockfish 28-72-0, with 0 losses
#:artificial intelligence
::: TaurineAndCode

Eve is a API Rest Python’s framework built for human beings
#:programming, codice, snippet
::: Linuxneitor ::: pypi_updates2

A Friendly Introduction to Mathematical Logic
#:manuali, how to
::: jaotwits

Anche Berlusconi salta sul carro dell’allarme fake news
#:fake news, bufale
::: fabiochiusi ::: fabiochiusi

Meet the men and women behind the iPhone X
#:ditte
::: SCMP_News

Nothing’s more relaxing than creating fractals after trying to put the kid to sleep for an hour or more!
#:lisp(s)
::: sourav_datta

Roughly 12% of Americans do not use the internet. What happens when you give some of those people internet-connect devices for the first time?
#:Web, Internet
::: JannaQ

Linux commands: a practical reference
#:sistemi operativi
::: UnixToolTip

Using Haskell on the frontend
#:programmazione funzionale #:Web, Internet
::: Jose_A_Alonso

learn elm: discover why people are switching to Elm and how you can get started today!
#:programmazione funzionale
::: Jose_A_Alonso

ReactOS 0.4.7 Released
#:sistemi operativi
::: Slashdot

Incredible story about how a restaurant that doesn’t exist became top rated on TripAdvisor
#:fake news, bufale #:social media
::: alexhaederli

la sensazione è che il punto delicato dell’accumulazione dei dati e del loro utilizzo sia trattato con superficialità, come una questione economica o di efficientismo nello sfruttamento del Big Data, senza alcuna attenzione ai diritti fondamentali che sono sottesi
#:dati, raccolta
::: CBlengio

Top 15 resources for learning JavaScript
#:linguaggi di programmazione
::: lucaciavatta

#Facebook privacy activist @maxschrems launches NGO – None of Your Business @NOYBeu – to fund data lawsuits
#:sicurezza, spionaggio, virus
::: kamvoj

gtop: Awesome system monitoring dashboard for Linux/macOS Unix terminal
#:tools, componenti software
::: NixCraft

Free Algorithm Books for Download
si può vero? da verificare
#:manuali, how to
::: I am Programmer

Technically, it becomes impossible to censor these websites. As soon as we launch, people will be able to access Everipedia articles – and Wikipedia articles – and there’s absolutely nothing these countries can do about it
#:Web, Internet
::: fabiochiusi

New post: Installing Python Packages from a Jupyter Notebook It should be easy, but it isn’t…
ha generato una lunga stringa di commenti 😜
#:programming, codice, snippet
::: jakevdp

8 Ways to Become a Better Coder
#:programming, codice, snippet
::: RichRogersIoT

Google’s Mobile Search Results Now Include Videos Of Celebrities Answering Your Questions
mah… ipses dixits?
#:Web, Internet
::: Slashdot

Q&A: @timberners_lee on net neutrality and why he won’t have Alexa in the house
#:Web, Internet
::: WikiTribune

Inside Oracle’s Cloak-and-dagger Political War With Google
#:sicurezza, spionaggio, virus #:ditte
::: Slashdot

Here are the slides on how @swheritage can contribute to scientific reproducibility that are being presented to the #acmrepro workshop today
#:storia
::: rdicosmo

This is gold! ‘Emphatically titled’ paper requesting cancellation from mailing list by bogus journal gets accepted in said bogus journal
#:frodi
::: ABonisoli

Ciò che mi piace sempre di questa versione liberal dei fatti è l’inoppugnabile insieme di prove che si accompagnano alle affermazioni, che fanno escludere *radicalmente* sia propaganda sulla propaganda e interferenza straniera sull’interferenza straniera
dal #cazzaro cosa t’aspetti? e anche se è su carta è –come dire?
#:politica
::: fabiochiusi ::: fabiochiusi

A generative vision model that trains with high data efficiency and breaks text-based CAPTCHAs
#:artificial intelligence
::: gescher

He made a political joke in a private chat group. Chinese police jailed him for five days
#:censura
::: davidakaye

What happens when the government uses Facebook as a weapon?
#:social media #:politica
::: fabiochiusi

Marco Delmastro

Looks very promising! Very much needed in the unikernels world
#:sistemi operativi
::: stabellinist

Today marks the start of the 8th year of my illegal detention without charge in the UK
#:sicurezza, spionaggio, virus
::: JulianAssange

Science and Technology links (December 8th, 2017)
#:innovazioni, futuro
::: lemire

How Software Heritage (@SWHeritage) makes software citation more practical
#:storia
::: danielskatz

Clojure 1.9 is now available!
#:programmazione funzionale
::: cognitect

Apple Is Reportedly Buying Shazam For Nearly Half a Billion Dollars
#:ditte
::: Slashdot

Fun read, co-authored by @johnregehr: Vigorous Public Debates in Academic Computer Science
#:programming, codice, snippet
::: rakamaric

Emanuele Menietti

On a positive note, heartening to see the surge of interest in ML ethics, safety, and rigor at NIPS 2017
#:artificial intelligence
::: beenwrekt

The battle to harness the immense potential of #AI is this generation’s great Space Race
#:artificial intelligence
::: ianbremmer

Meet the man behind the most important tool in data science
#:programming, codice, snippet
::: dkopf

really enjoying these interviews by @jeanqasaur with people from the programming languages community
#:programming, codice, snippet
::: jakedonham

Ray: A Distributed Execution Framework for Emerging AI Applications (Ion Stoica)
#:artificial intelligence
::: Inside 233

A Machine Learning Approach to Database Indexes (Alex Beutel)
#:artificial intelligence
::: Inside 233

MOCHA: Federated Multi-Tasks Learning (Virginia Smith)
#:artificial intelligence
::: Inside 233

Accelerating Persistent Neural Networks at Datacenter Scale (Daniel Lo)
#:artificial intelligence
::: Inside 233

Systems ML workshop panel
#:artificial intelligence
::: Inside 233

The history of T – A remarkable Scheme predecessor
#:storia #:lisp(s)
::: _wilfredh

‘Process Doppelganging’ Attack Bypasses Most Security Products, Works On All Windows Versions
#:sicurezza, spionaggio, virus
::: Slashdot

Protip: When doing a big treason, don’t track changes in Microsoft Word
#:sicurezza, spionaggio, virus
::: oneunderscore__

Stopify – An experimental, web-based code editor
#:tools, componenti software
::: Donearm

BrewChain – NodeJS blockchain implementation
#:programming, codice, snippet
::: Donearm

Haskell – 57 – inizio – 5

Continuo da qui, copio qui.

List comprehesion
If you’ve ever taken a course in mathematics, you’ve probably run into set comprehensions. They’re normally used for building more specific sets out of general sets. A basic comprehension for a set that contains the first ten even natural numbers is

The part before the pipe is called the output function, x is the variable, N is the input set and x <= 10 is the predicate. That means that the set contains the doubles of all natural numbers that satisfy the predicate.

If we wanted to write that in Haskell, we could do something like take 10 [2,4..]. But what if we didn’t want doubles of the first 10 natural numbers but some kind of more complex function applied on them? We could use a list comprehension for that. List comprehensions are very similar to set comprehensions. We’ll stick to getting the first 10 even numbers for now. The list comprehension we could use is [x*2 | x <- [1..10]]. x is drawn from [1..10] and for every element in [1..10] (which we have bound to x), we get that element, only doubled. Here’s that comprehension in action.

Prelude> [x*2 | x <- [1..10]]
[2,4,6,8,10,12,14,16,18,20]

As you can see, we get the desired results. Now let’s add a condition (or a predicate) to that comprehension. Predicates go after the binding parts and are separated from them by a comma. Let’s say we want only the elements which, doubled, are greater than or equal to 12.

Prelude> [x*2 | x <- [1..10], x*2 >= 12]
[12,14,16,18,20]

Cool, it works. How about if we wanted all numbers from 50 to 100 whose remainder when divided with the number 7 is 3? Easy.

Prelude> [ x | x <- [50..100], x `mod` 7 == 3]
[52,59,66,73,80,87,94]

Naturalmente si può usare la notazione prefissa che a me piace di più:

Prelude> [ x | x <- [50..100], mod x 7 == 3]
[52,59,66,73,80,87,94]

Success! Note that weeding out lists by predicates is also called filtering. We took a list of numbers and we filtered them by the predicate. Now for another example. Let’s say we want a comprehension that replaces each odd number greater than 10 with “BANG!” and each odd number that’s less than 10 with “BOOM!”. If a number isn’t odd, we throw it out of our list. For convenience, we’ll put that comprehension inside a function so we can easily reuse it.

Prelude> boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x]

The last part of the comprehension is the predicate. The function odd returns True on an odd number and False on an even one. The element is included in the list only if all the predicates evaluate to True.

Prelude> boomBangs [7..13]
["BOOM!","BOOM!","BANG!","BANG!"]

We can include several predicates. If we wanted all numbers from 10 to 20 that are not 13, 15 or 19, we’d do:

Prelude> [x | x <- [10..20], x /= 13, x /= 15, x /= 19]
[10,11,12,14,16,17,18,20]

Not only can we have multiple predicates in list comprehensions (an element must satisfy all the predicates to be included in the resulting list), we can also draw from several lists. When drawing from several lists, comprehensions produce all combinations of the given lists and then join them by the output function we supply. A list produced by a comprehension that draws from two lists of length 4 will have a length of 16, provided we don’t filter them. If we have two lists, [2,5,10] and [8,10,11] and we want to get the products of all the possible combinations between numbers in those lists, here’s what we’d do.

Prelude> [x*y | x <- [2,5,10], y <- [8,10,11]]
[16,20,22,40,50,55,80,100,110]

As expected, the length of the new list is 9. What if we wanted all possible products that are more than 50?

Prelude> [ x*y | x <- [2,5,10], y <- [8,10,11], x*y > 50]
[55,80,100,110]

How about a list comprehension that combines a list of adjectives and a list of nouns … for epic hilarity.

Prelude> nouns = ["hobo","frog","pope"]
Prelude> adjectives = ["lazy","grouchy","scheming"]
Prelude> [adjective ++ " " ++ noun | adjective <- adjectives, noun <- nouns]
["lazy hobo","lazy frog","lazy pope","grouchy hobo","grouchy frog","grouchy pope",
"scheming hobo","scheming frog","scheming pope"]

I know! Let’s write our own version of length! We’ll call it length'.

Prelude> length' xs = sum [1 | _ <- xs]

_ means that we don’t care what we’ll draw from the list anyway so instead of writing a variable name that we’ll never use, we just write _. This function replaces every element of a list with 1 and then sums that up. This means that the resulting sum will be the length of our list.

Just a friendly reminder: because strings are lists, we can use list comprehensions to process and produce strings. Here’s a function that takes a string and removes everything except uppercase letters from it.

Prelude> removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']]

Testing it out:

Prelude> removeNonUppercase "Hahaha! Ahahaha!"
"HA"
Prelude> removeNonUppercase "IdontLIKEFROGS"
"ILIKEFROGS"

The predicate here does all the work. It says that the character will be included in the new list only if it’s an element of the list ['A'..'Z']. Nested list comprehensions are also possible if you’re operating on lists that contain lists. A list contains several lists of numbers. Let’s remove all odd numbers without flattening the list.

Prelude> xxs = [[1,3,5,2,3,1,2,4,5],[1,2,3,4,5,6,7,8,9],[1,2,4,2,1,6,3,1,3,2,3,6]]
Prelude> [ [ x | x <- xs, even x ] | xs <- xxs]
[[2,2,4],[2,4,6,8],[2,4,2,6,2,6]]

You can write list comprehensions across several lines. So if you’re not in GHCI, it’s better to split longer list comprehensions across multiple lines, especially if they’re nested.

🤩

Bitcoin – cosa mi aspetta?

Prima di cominciare a scrivere una precisazione: non ne so niente (nada, zilch) di economia. Questo post è solo per dire come la penso in questi giorni quando il valore della moneta virtuale (o come cribbio si chiama) sta skyrockettando oltre ogni previsione. Roba che neanche zio Paperone … E manca tuttora una qualsiasi dichiarazione della Banda Bassotti. Niente buio completo.

Oggi girulando as usual on teh toobz ho racimolato qualche dritta, opinione, pensiero, eccone gli URLs

Adesso il mio sentimento –tenere ben presente quanto scritto nell’incipit, nèh!
Senza andare troppo lontano a ravanare con Olanda e tulipani credo tutti abbiano qualche cognizione del crollo di Wall Street del 1929 e di quello delle dot-com del 2000: On March 10, 2000, the NASDAQ Composite peaked at 5,132.52, but fell 78% in the following 30 months. Ah! ce n’è stato un altro nel 2008-9, quello dal quale noi non ci siamo ancora ripresi (e chissà se…).

Ecco, a me sembra che presto –2018?– la storia si ripeterà. Peggiore. Assay.

Bon, l’ho detto, non me la prendo se sarò smentito. Anzi 😋

No, non ho idea di cosa capiterà quando scoppierà la bolla. Ma sono preoccupato proprio per questo. E perché è grossa-grossa (assay) 😯

🤩