I'm trying to create a data type representing an objects position that can 'GO', 'STOP', move 'FORWARD', and move 'BACKWARD'. I can't figure out how to write the deriving instance of 'Eq' and 'Show' for the functions FORWARD and BACKWARD.
data Moves = GO
| STOP
| FORWARD { f :: Int -> Int -> Int }
| BACKWARD { g :: Int -> Int -> Int }
deriving (Eq, Show)
instance (Eq Moves) where
FORWARD a == FORWARD b = True
FORWARD a == BACKWARD b = True
BACKWARD a == BACKWARD b = True
BACKWARD a == FORWARD b = True
_ == _ = False
The logic for the instance doesn't matter at the moment I just can't figure out how to get it to compile. Thanks
When you automatically derive various standard typeclasses via the deriving
clause, this relies on the individual fields or branches of the data structure already having instances for those classes. Since functions have no default instance for either Eq
or Show
(which is perfectly reasonable, there's no obvious canonical way to either determine if 2 arbitrary functions are equal*, or to print them as strings), and your datatype includes 2 fields whose values are functions, it's impossible for Haskell to derive Eq
and Show
instances, and this is what the compilation error is about.
The solution is simply to remove the deriving (Eq, Show)
part - you don't need this anyway if you're going to define your own custom instances. (The only reason to put a deriving
clause is if you need an instance and are happy with the "standard" one - which a lot of the time you would be. Here though, you seem to be wanting to implement your own instances with non-standard logic. That is fine if your use-case demands it.)
*actually in mathematics it's clear what equality of functions means, functions are defined by their graph, which means that for two functions to be equal, they must give the same output for every possible input value. That's still theoretically important in Haskell programming (since the "laws" for various type classes require various functions to be equal), but it's not possible to implement in any reasonable way in general, not least because some functions can run forever without giving a result, so actually computing equality of functions in general is rather stronger than solving the Halting Problem !)
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.