Haskell "No instance for (Eq a) arising from a use of `/='" - haskell

I'm just starting to get into the world of functional programming in a class. As a part of an assignment, we have to write a function that determines if a list is a singleton or not (if the list has exactly 1 element inside of it)
I've written the function and it works perfectly fine:
singleton x = x /= [] && x == take 1 (x)
If I call singleton [1] it returns true as expected.
If I call singleton [] or singleton [1,2,3] it returns false as expected.
However, my professor wants us to properly document the code with (I'm not exactly sure what this is called, but it tell haskell what to expect as input and output from the function):
singleton :: [a] -> Bool
As far as I can tell, this should work, but as soon as I have this, the compiler says "No instance for (Eq a) arising from a use of '/='"
Could anyone point me in the right direction to get the code compiled with that (I really have no clue what it's called) bit of function declaration?
Thanks!

In your code:
singleton x = x /= [] && x == take 1 (x)
you do an equality test, x == take 1 x. This does a comparison of all the elements in the list to see if they are equal, so your elements must be "comparable". That's what Eq a is all about. The following fixes your problem:
singleton :: (Eq a) => [a] -> Bool
singleton x = x /= [] && x == take 1 (x)
But that is probably not what you want, since then your types must be comparable. You should be able to check if a list is a singleton without comparing the elements. But that is an exercise for you. Hint: It involves pattern matching.

Related

Learning Haskell: where-clause variable x, where does it come from?

I am learning Haskell and this will be my first post.
In the great online book http://learnyouahaskell.com/syntax-in-functions#where there is the example largestDivisble. In the where-clause the variable x is introduced but where does it come from? Untill now the variables where bounded in the pattern-matching part of the function body.
As I now interpret it:
the part where p x declares the function p and the application of some variable x. In the body filter p [some-list], the some-list stands for x.
I think this is all a bit fuzzy. Can someone help me out with a explanation of this piece of code?
largestDivisible :: (Integral a) => a
largestDivisible = head (filter p [100000,99999..])
where p x = x `mod` 3829 == 0
x there is just the function argument. It's entirely local to the definition of p.
You could have defined it as a separate, top-level function, like this:
p :: (Integral a) => a -> Bool
p x = x `mod` 3829 == 0
and note that the type signature here isn't required, it's just good practice to include it for a top level function. The definition of p in the where clause is identical, including x being a local name for the function argument. The only difference between the two is that a function defined in a where clause is local to the definition that includes that clause, and can't be accessed outside.

Understanding Haskell Type Class use in Type Declarations

When we have a function that compares two things using the == comparison operator we add something like Eq a => a... to the type declaration; but this doesn't always seem to be the case.
For example, given the following function:
tail' xs = if length xs == 0
then []
else drop 1 xs
We make use of the == comparison operator, so I assumed the correct type decalaration would be:
tail':: (Eq a) => [a] -> [a]
However, running :t tail' tells me that the correct type decalartion is:
tail':: [a] -> [a]
Why is this the case? Why isn't Eq required in the type declaration?
Eq a => t says that a must be an instance of Eq in the type t. A type being an instance of Eq means that == is defined for that type. But in your definition of tail', you never use == on an a, not even by proxy. The actual use of == is in length xs == 0. The type of length xs (and 0) is Int, and Int is already an instance of Eq, so we already know it has == defined. Since you never use == on an a, you don't need an Eq a constraint.
If, however, you had said xs == [], which seems equivalent (both test whether a list is empty), you would have incurred an Eq a constraint. This is because == on [a] requires an Eq a constraint since it uses == on each list's entries to compare the lists. Since you can use length xs == 0 (or, even better, null xs), though, this added constraint is spurious and should be avoided.
(As an aside, drop 1 [] = [] so you don't even need your if, but that isn't relevant to the question asked.)

"For all" statements in Haskell

I'm building comfort going through some Haskell toy problems and I've written the following speck of code
multipOf :: [a] -> (Int, a)
multipOf x = (length x, head x)
gmcompress x = (map multipOf).group $ x
which successfully preforms the following operation
gmcompress [1,1,1,1,2,2,2,3] = [(4,1),(3,2),(1,3)]
Now I want this function to instead of telling me that an element of the set had multiplicity 1, to just leave it alone. So to give the result [(4,1),(3,2),3] instead. It be great if there were a way to say (either during or after turning the list into one of pairs) for all elements of multiplicity 1, leave as just an element; else, pair. My initial, naive, thought was to do the following.
multipOf :: [a] -> (Int, a)
multipOf x = if length x = 1 then head x else (length x, head x)
gmcompress x = (map multipOf).group $ x
BUT this doesn't work. I think because the then and else clauses have different types, and unfortunately you can't piece-wise define the (co)domain of your functions. How might I go about getting past this issue?
BUT this doesn't work. I think because the then and else clauses have different types, and unfortunately you can't piece-wise define the (co)domain of your functions. How might I go about getting past this issue?
Your diagnosis is right; the then and else must have the same type. There's no "getting past this issue," strictly speaking. Whatever solution you adopt has to use same type in both branches of the conditional. One way would be to design a custom data type that encodes the possibilities that you want, and use that instead. Something like this would work:
-- | A 'Run' of #a# is either 'One' #a# or 'Many' of them (with the number
-- as an argument to the 'Many' constructor).
data Run a = One a | Many Int a
But to tell you the truth, I don't think this would really gain you anything. I'd stick to the (Int, a) encoding rather than going to this Run type.

Variable scope in a higher-order lambda function

In working through a solution to the 8 Queens problem, a person used the following line of code:
sameDiag try qs = any (\(colDist,q) -> abs (try - q) == colDist) $ zip [1..] qs
try is an an item; qs is a list of the same items.
Can someone explain how colDist and q in the lambda function get bound to anything?
How did try and q used in the body of lambda function find their way into the same scope?
To the degree this is a Haskell idiom, what problem does this design approach help solve?
The function any is a higher-order function that takes 2 arguments:
the 1st argument is of type a -> Bool, i.e. a function from a to Bool
the 2nd argument is of type [a], i.e. a list of items of type a;
i.e. the 1st argument is a function that takes any element from the list passed as the 2nd argument, and returns a Bool based on that element. (well it can take any values of type a, not just the ones in that list, but it's quite obviously certain that any won't be invoking it with some arbitrary values of a but the ones from the list.)
You can then simplify thinking about the original snippet by doing a slight refactoring:
sameDiag :: Int -> [Int] -> Bool
sameDiag try qs = any f xs
where
xs = zip [1..] qs
f = (\(colDist, q) -> abs (try - q) == colDist)
which can be transformed into
sameDiag :: Int -> [Int] -> Bool
sameDiag try qs = any f xs
where
xs = zip [1..] qs
f (colDist, q) = abs (try - q) == colDist)
which in turn can be transformed into
sameDiag :: Int -> [Int] -> Bool
sameDiag try qs = any f xs
where
xs = zip [1..] qs
f pair = abs (try - q) == colDist) where (colDist, q) = pair
(Note that sameDiag could also have a more general type Integral a => a -> [a] -> Bool rather than the current monomorphic one)
— so how does the pair in f pair = ... get bound to a value? well, simple: it's just a function; whoever calls it must pass along a value for the pair argument. — when calling any with the first argument set to f, it's the invocation of the function any who's doing the calling of f, with individual elements of the list xs passed in as values of the argument pair.
and, since the contents of xs is a list of pairs, it's OK to pass an individual pair from this list to f as f expects it to be just that.
EDIT: a further explanation of any to address the asker's comment:
Is this a fair synthesis? This approach to designing a higher-order function allows the invoking code to change how f behaves AND invoke the higher-order function with a list that requires additional processing prior to being used to invoke f for every element in the list. Encapsulating the list processing (in this case with zip) seems the right thing to do, but is the intent of this additional processing really clear in the original one-liner above?
There's really no additional processing done by any prior to invoking f. There is just very minimalistic bookkeeping in addition to simply iterating through the passed in list xs: invoking f on the elements during the iteration, and immediately breaking the iteration and returning True the first time f returns True for any list element.
Most of the behavior of any is "implicit" though in that it's taken care of by Haskell's lazy evaluation, basic language semantics as well as existing functions, which any is composed of (well at least my version of it below, any' — I haven't taken a look at the built-in Prelude version of any yet but I'm sure it's not much different; just probably more heavily optimised).
In fact, any is simple it's almost trivial to re-implement it with a one liner on a GHCi prompt:
Prelude> let any' f xs = or (map f xs)
let's see now what GHC computes as its type:
Prelude> :t any'
any' :: (a -> Bool) -> [a] -> Bool
— same as the built-in any. So let's give it some trial runs:
Prelude> any' odd [1, 2, 3] -- any odd values in the list?
True
Prelude> any' even [1, 3] -- any even ones?
False
Prelude> let adult = (>=18)
Prelude> any' adult [17, 17, 16, 15, 17, 18]
— see how you can sometimes write code that almost looks like English with higher-order functions?
zip :: [a] -> [b] -> [(a,b)] takes two lists and joins them into pairs, dropping any remaining at the end.
any :: (a -> Bool) -> [a] -> Bool takes a function and a list of as and then returns True if any of the values returned true or not.
So colDist and q are the first and second elements of the pairs in the list made by zip [1..] qs, and they are bound when they are applied to the pair by any.
q is only bound within the body of the lambda function - this is the same as with lambda calculus. Since try was bound before in the function definition, it is still available in this inner scope. If you think of lambda calculus, the term \x.\y.x+y makes sense, despite the x and the y being bound at different times.
As for the design approach, this approach is much cleaner than trying to iterate or recurse through the list manually. It seems quite clear in its intentions to me (with respect to the larger codebase it comes from).

implementing indexOf in Haskell

I'm going through the Learn You a Haskell tutorial and attempted to modify the elem' function from the section on Recursion.
The original elem' function is:
elem' :: (Eq a) => a -> [a] -> Bool
elem' a [] = False
elem' a (x:xs)
| a == x = True
| otherwise = a `elem'` xs
My indexOf function is:
indexOf :: (Eq a, Integral s) => a -> [a] -> s -> s
indexOf _ [] _ = -1
indexOf a (x:xs) s
| a == x = s
| otherwise = indexOf a xs s+1
The function should return either the index of the element in the list, or -1 if the element is not found.
At the end of my .hs file I test the function with:
main = putStrLn(show(indexOf 7 [1,2,3] 0))
The function works correctly for finding values that appear in the list. However, for the test written above, instead of returning -1, it prints 2. The return value seems to always be the list length minus one.
After encountering the edge condition (empty list), I would expect the -1 return value to propagate all the way back upwards through the call stack. Where's my mistake?
You've got a precedence problem. Function application binds more tightly than (+), so the otherwise case is being parsed as (index' a xs s) + 1.
There is one simple change you could make to the example above, which would be almost guaranteed to fix your bug. Change the return type to Maybe a, and return Nothing upon failure. While this alone won't fix your bug, it gives the compiler enough information that it will lead you down the correct path that you will be able to fix it yourself.
Returning -1 on failure is a very "c" thing to do, and it is error prone. In your case, the compiler is confusing -1 with an actual array index, which can be added to as you go back up through the recursive calls. (I can see that this was not your intention from the signature, but this is how the compiler interpreted what you have done).
(One added advantage- Once you master the art of using correct types, you will soon realize how hard it is to work with functions of the type a->Maybe b, or more generally a->m b, where m is some wrapper type.... This will bring you to the doorstep of understanding what and why we use monads).

Resources