1
votes

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!

1
I don't think it's the same, because in that other question the function actually needs the Eq a, while in this one it can be rewritten to avoid it.Ørjan Johansen
@ØrjanJohansen I think it's the same. Your function needs it, too. When you check whether [a] == [a], that implies checking the equality of a.piojo
@piojo The point is that you can write the function in such a way that it gets the type [a] -> Bool and not (Eq a) => [a] -> Bool.Hashmush
By the way, the [a] -> Bool part is called a type signature.Lambda Fairy

1 Answers

7
votes

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.