简体   繁体   中英

Haskell “No instance for (Eq a) arising from a use of `/='”

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM