How does these two notations differ in Haskell? - haskell

I am new to Haskell and still kind of confused with some notations.
In the function header, i know that
func :: [Int] -> Int
indicates that the input is a list of integers and the output is an integer.
How does this differ from
func :: (Ord a) => [a] -> a
I am asking because they seem to be same, and I wonder why we use different notations for something identical.

The first one is very simple and as you have said, it takes a list of Int and returns a single Int.
The second one, however, can accept many different types for its input (including types you define yourself).
The key is (Ord a). What this is saying is that it has to be a list of orderable types, and if it satisfies that requirement then it is a valid type that can be passed into this particular function.
The Ord typeclass includes the following members:
<
<=
>
>=
So
func :: (Ord a) => [a] -> a
could potentially be a function that takes a list of orderable types and returns the maximum member of that list, as an example. This could be [Int], [Integer], [Float], and many other things.

Related

Type variables in function signature

If I do the following
functionS (x,y) = y
:t functionS
functionS :: (a, b) -> b
Now with this function:
functionC x y = if (x > y) then True else False
:t function
I would expect to get:
functionC :: (Ord a, Ord b) => a -> b -> Bool
But I get:
functionC :: Ord a => a -> a -> Bool
GHCI seems to be ok with the 2 previous results, but why does it give me the second? Why the type variable a AND b aren't defined?
I think you might be misreading type signatures. Through no fault of your own––the examples you using to inform your thinking are kind of confusing. In particular, in your tuple example
functionS :: (a,b) -> b
functionS (x,y) = y
The notation (_,_) means two different things. In the first line, (a,b) refers to a type, the type of pairs whose first element has type a and second has type b. In the second line, (x,y) refers to a specfiic pair, where x has type a and y has type b. While this "pun" provides a useful mnemonic, it can be confusing as you are first getting the hang of it. I would rather that the type of pairs be a regular type constructor:
functionS :: Pair a b -> b
functionS (x,y) = y
So, moving on to your question. In the signature you are given
functionC :: Ord a => a -> a -> Bool
a is a type. Ord a says that elements of the type a are orderable with respect to each other. The function takes two arguments of the same type. Some types that are orderable are Integer (numerically), String (lexicographically), and a bunch of others. That means that you can tell which of two Integers is the smaller, or which of two Strings are the smaller. However we don't necessarily know how to tell whether an Integer is smaller than a String (and this is good! Have you seen what kinds of shenanigans javascript has to do to support untyped equality? Haskell doesn't have to solve this problem at all!). So that's what this signature is saying –– there is only one single orderable type, a, and the function takes two elements of this same type.
You might still be wondering why functionS's signature has two different type variables. It's because there is no constraint confining them to be the same, such as having to order them against each other. functionS works equally well with a pair where both components are integers as when one is an integer and the other is a string. It doesn't matter. And Haskell always picks the most general type that works. So if they are not forced to be the same, they will be different.
There are more technical ways to explain all this, but I felt an intuitive explanation was in order. I hope it's helpful!

Type of any in Haskell?

I've recently started trying to learn Haskell by reading LearnYouAHaskell and random articles from the internet.
I'm having hard time understanding more sophisticated function types.
Some examples that I understand.
> :t map
map :: (a -> b) -> [a] -> [b]
It takes in a function (which takes a and gives out b, i.e a and b can be of different types) and a list of a's and return a list of b's.
> :t fst
fst :: (a, b) -> a
Takes in a tuple of 2 elements (allows different types) and returns the first one.
> :t any
At a higher level, I understand any. It takes in a function and a list and returns true if any of the list entries return true for that particular function. I've used it in Python and JavaScript as well.
Questions
I don't understand how does any :: Foldable t => (a -> Bool) -> t a -> Bool
translate to the above.
(a -> Bool) is the predicate. Takes in an argument and returns true or false.
t a -> Bool Bool is the end result of any. According to my understanding t and a represent the predicate and the list. Why aren't they separated by a ->
How to go about understanding type signatures in general and how to dig deeper so that I can approach them myself?
any :: Foldable t => (a -> Bool) -> t a -> Bool
Here Foldable t means, that t is an instance of type class Foldable.
Foldable is a type class and if type t is an instance of the type class Foldable we know from the t a part of the signature or from the definition of the type class Foldable, that t is actually a type constructor.
So t a is a type and therefore t a -> Bool is a function, that maps a value of type t a to Bool. This function will be closure, which will
apply the predicate to each "element" of the value of type t a, until it finds one, that yields True under the predicate or it doesn't find such an element returning either True or False in the respective cases. (The actual implementation might be very different.)
For example [] is an instance of the type class Foldable and therefore t a could be a list of something. In this case, we can also write [a] instead of [] a.
But there are other type constructors, which can be instances of Foldable, for example some kinds of trees.
It might be helpful to note that until recently, the signature was actually
any :: (a -> Bool) -> [a] -> Bool
This was generalised during the Foldable Traversable in Prelude proposal: now the container of values need not be a list, but can as well be e.g. an array:
Prelude> import qualified Data.Vector as Arr
Prelude Arr> :set -XOverloadedLists
Prelude Arr> let a = [1,2,3] :: Arr.Vector Int
Prelude Arr> any (>2) a
True
Type signature is a mark up designation of the function indicating the types to be processed and how the function can be partially applied.
Foldable t => (a -> Bool) -> t a -> Bool
By Foldable t it first says any function can work with any data type which is an instance of Foldable type class.
The first parameter, (a -> Bool) is obviously a function which takes a single element (a) from our foldable data type and returns a Bool type value. It's the the callback of .some(callback) in JavaScript. When you apply this parameter to any you will be returned with a function of type;
t a -> Bool
Now we are left with a single function which takes only one parameter and returns a Bool type (True or False) value. Again t a is a data type which is a member of the Foldable type class. It can be a [] but a Tree too provided that the data type has foldMap function defined under an instance to Foldable. It's the myArr part in JavaScript's myArr.some(callback) except that it doesn't have to be an array.
t a isn't separated by a -> because the t a is the instance of foldable, ex: List a, or Tree a. Let's go back to map for a second. The version you gave is specialized to lists; a more general version (which, as an accident of history, is called fmap in most versions of Haskell) has type fmap :: Functor f => (a->b) -> f a -> f b. Where is your input list in this signature? It's the f a. Now, returning to any the t a is the second argument, the instance of Foldable you're folding over, the list or tree or whatever.
You'll read that all functions in Haskell really have only 1 argument, and we're seeing that here. any takes it's first argument (the predicate) and returns a function that takes a foldable (the list, tree, etc) and returns a Bool.
t a does not represent the predicate and the list. As you've already correctly pointed out before, (a -> Bool) is the predicate. t a just represents the list, except it doesn't have to be a list (that's why it's t a instead of [a]). t can be any Foldable, so it could be [], but it could also be some other collection type or Maybe.

Haskell-(Type declaration) what is "a"?

This is perhaps a very basic question, but, nevertheless, it does not seem to have been covered on SO.
I recently took up Haskell and up until now type declarations consisted of mostly the following:
Int
Bool
Float
etc, etc
Now I am getting into lists and I am seeing type declarations that use a, such as in the following function that iterates through an associative list:
contains :: Int -> [(Int,a)] -> [a]
contains x list = [values | (key,values)<-list, x==key]
Can someone provide an explanation as to what this a is, and how it works? From observation it seems to represent every type. Does this mean I can input any list of any type as parameter?
Yes, you're right, it represents "any type" - the restriction being that all as in a given type signature must resolve to the same type. So you can input a list of any type, but when you use contains to look up a value in the list, the value you look up must be the same type as the elements of the list - which makes sense of course.
In Haskell, uppercase types are concrete types (Int, Bool) or type constructors (Maybe, Either) while lowercase types are type variables. A function is implicitly generic in all the type variables it uses, so this:
contains :: Int -> [(Int, a)] -> [a]
Is shorthand for this*:
contains :: forall a. Int -> [(Int, a)] -> [a]
In C++, forall is spelled template:
template<typename a>
list<a> contains(int, list<pair<int, a>>);
In Java and C#, it’s spelled with angle brackets:
list<a> contains<a>(int, list<pair<int, a>>);
Of course, in these languages, generic type variables are often called T, U, V, while in Haskell they’re often called a, b, c. It’s just a difference of convention.
* This syntax is enabled by the -XExplicitForAll flag in GHC, as well as other extensions.

How to Interpret (Eq a)

I need to create a function of two parameters, an Int and a [Int], that returns a new [Int] with all occurrences of the first parameter removed.
I can create the function easily enough, both with list comprehension and list recursion. However, I do it with these parameters:
deleteAll_list_comp :: Integer -> [Integer] -> [Integer]
deleteAll_list_rec :: (Integer -> Bool) -> [Integer] -> [Integer]
For my assignment, however, my required parameters are
deleteAll_list_comp :: (Eq a) => a -> [a] -> [a]
deleteAll_list_rec :: (Eq a) => a -> [a] -> [a]
I don't know how to read this syntax. As Google has told me, (Eq a) merely explains to Haskell that a is a type that is comparable. However, I don't understand the point of this as all Ints are naturally comparable. How do I go about interpreting and implementing the methods using these parameters? What I mean is, what exactly are the parameters to begin with?
#groovy #pelotom
Thanks, this makes it very clear. I understand now that really it is only asking for two parameters as opposed to three. However, I still am running into a problem with this code.
deleteAll_list_rec :: (Eq a) => a -> [a] -> [a]
delete_list_rec toDelete [] = []
delete_list_rec toDelete (a:as) =
if(toDelete == a) then delete_list_rec toDelete as
else a:(delete_list_rec toDelete as)
This gives me a "The type signature for deleteAll_list_rec
lacks an accompanying binding" which makes no sense to me seeing as how I did bind the requirements properly, didn't I? From my small experience, (a:as) counts as a list while extracting the first element from it. Why does this generate an error but
deleteAll_list_comp :: (Eq a) => a -> [a] -> [a]
deleteAll_list_comp toDelete ls = [x | x <- ls, toDelete==x]
does not?
2/7/13 Update: For all those who might stumble upon this post in the future with the same question, I've found some good information about Haskell in general, and my question specifically, at this link : http://learnyouahaskell.com/types-and-typeclasses
"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."
One way to think of the parameters could be:
(Eq a) => a -> [a] -> [a]
(Eq a) => means any a's in the function parameters should be members of the
class Eq, which can be evaluated as equal or unequal.*
a -> [a] means the function will have two parameters: (1) an element of
type a, and (2) a list of elements of the same type a (we know that
type a in this case should be a member of class Eq, such as Num or
String).
-> [a] means the function will return a list of elements of the same
type a; and the assignment states that this returned list should
exclude any elements that equal the first function parameter,
toDelete.
(* edited based on pelotom's comment)
What you implemented (rather, what you think you implemented) is a function that works only on lists of Integers, what the assignment wants you to do is create one that works on lists of all types provided they are equality-comparable (so that your function will also work on lists of booleans or strings). You probably don't have to change a lot: Try removing the explicit type signatures from your code and ask ghci about the type that it would infer from your code (:l yourfile.hs and then :t deleteAll_list_comp). Unless you use arithmetic operations or similar things, you will most likely find that your functions already work for all Eq a.
As a simpler example that may explain the concept: Let's say we want to write a function isequal that checks for equality (slightly useless, but hey):
isequal :: Integer -> Integer -> Bool
isequal a b = (a == b)
This is a perfectly fine definition of isequal, but the type constraints that I have manually put on it are way stronger than they have to. In fact, in the absence of the manual type signature, ghci infers:
Prelude> :t isequal
isequal :: Eq a => a -> a -> Bool
which tells us that the function will work for all input types, as long as they are deriving Eq, which means nothing more than having a proper == relation defined on them.
There is still a problem with your _rec function though, since it should do the same thing as your _comp function, the type signatures should match.

How do I determine the type of constant expressions in Haskell?

I am trying to revise for my functional programming exam, and am stumped on the first questions on past papers, and yes, we arent allowed solution sheets, here is an example of the 1st question on a past paper.
For each of the following expressions give its type in Haskell (for an expression that has many types, just give one type).
(True, "hello", 42)
[42, 4, 2]
length [True]
filter even
I think personally that the answer for one and two would be a tuple of bool, String and int and a list of ints respectively, is this correct to assume? and secondly how would you answer 3 and 4, i am sure length True just outputs a list of all elements that are of that length, and that filter even just alters a list of ints to a list that are of all even numbers, though how could i show this as an answer?
If you want to get types of variables offline with ghci you have to type
:t expression
if you want to create variables in ghci, you have to use let without using 'in' (as in do notation for monads, I don't know if you have seen them yet) :
let var = expr
If you check it all by yourself, you should be able to remember it more easily for your exams. (good luck for it ;))
length [True] will be Int, and it would return 1. You can check that with ghci or lambdabot.
filter even will be (Integral a) => [a] -> [a]
for example, [Int] -> [Int]
And I think this is kind of pointless because lambdabot can tell all those things to you.
To be precise, the type of [42, 4, 2] is going to be
Num a => [a]
This is because an integer literal in Haskell is treated as having an implicit "fromIntegral" in front of it, so the real expression is [fromIntegral 42, fromIntegral 4, fromIntegral 2].
"fromIntegral" is part of the Num class, and has the type
fromIntegral :: (Integral a, Num b) => a -> b
This says that it converts an instance of some Integral type (i.e. Int or Integer) into an arbitrary other numeric type (Int, Float, Double, Complex ...). This is why you can say something like "43.2 + 1" without getting a type error.
"length [True]" is going to have type Int, because "length" has type "[a] -> Int", and the argument (a list of Bool) is provided.
"filter even" is a little bit more complicated. Start with the type of "filter":
filter :: (a -> Bool) -> [a] -> [a]
The first parameter (the bit in brackets) is itself a function that takes a list item and returns a Bool. Remember that the "->" operator in Haskell types is right associative, so if you put in the implied brackets you see that the type is:
filter :: (a -> Bool) -> ([a] -> [a])
In other words if you give it the first argument, you get back a new function that expects the second argument. In this case the first argument is:
even :: (Integral a) => a -> Bool
This introduces a slight wrinkle: "even" requires its argument to be an Integral type (i.e. Int or Integer, as above), so this constraint has to be propagated to the result. If it were not then you could write this:
filter even "foo"
Hence the answer is:
filter even :: (Integral a) => [a] -> [a]
You can see that the Integral constraint comes from the type of "even", while the rest of the type comes from "filter".

Resources