I'm trying to write a simple genetic algorithm in Haskell. I figured the first step should be to make a typeclass for individuals that are 'genetic', like so:
class Genetic a where
fitness :: (Ord b) => a -> b
This seems reasonable to me - I don't necessarily want to restrict fitness functions to a type like Float
or Double
, and conceptually all a fitness function should do is provide an ordering of the individuals.
However, when I implement this typeclass for a String
wrapper:
data DNA = DNA String
instance Genetic DNA where
fitness (DNA s) = length s
I see the following error in GHC:
Could not deduce (b ~ Int)
from the context (Ord b)
bound by the type signature for fitness :: Ord b => DNA -> b
Is this not how I should define typeclass functions? Do I have to restrict the function to a specific concrete type, or provide another type variable to the typeclass constructor?
fitness
must be able to fabricate a value of any orderable type and return it. Note,Void
(the type with no values) is orderable, so this is impossible. You probably want to parameterizeGenetic
on the order space:class (Ord b) => Genetic b a where fitness :: a -> b
– luquiMultiParamTypeclasses
extension is pretty common to use – Daniel Gratzer