I'm trying to create a simple Haskell evolutionary algorithm and I'm trying to make it as general as possible. This was originally an assignment which I solved with Python at the time which I wanted to go back to when I had more time and solve in Haskell. The assignment needed the code to be very flexible and I have tried to recreate that in my preliminary Haskell implementation.
In the code below you can see the error GHC is giving me:
Ambiguous type variable 'a0' in the constraint:
(Genome a0) arising from a use of 'crossover'
Probable fix: add a type signature that fixes these type variable(s)
In the expression: crossover cross (genome dad) (genome mom)
In the first argument of 'mapM', namely
'(\ (dad, mom) -> crossover cross (genome dad) (genome mom))'
In a stmt of a 'do' block:
children <- mapM
(\ (dad, mom) -> crossover cross (genome dad) (genome mom)) parents
I have the following class declarations:
class (Eq a, Show a) => Genome a where
crossover :: (Fractional b) => b -> a -> a -> IO (a, a)
mutate :: (Fractional b) => b -> a -> IO a
develop :: (Phenotype b) => a -> b
class (Eq a, Show a) => Phenotype a where
--In case of Coevolution where each phenotype needs to be compared to every other in the population
fitness :: [a] -> a -> Int
genome :: (Genome b) => a -> b
The code that is giving me the problem is:
breed :: (Phenotype b) => [(b, b)] -> Double -> Double -> IO [b]
breed parents cross mute = do
children <- mapM (\ (dad, mom) -> crossover cross (genome dad) (genome mom)) parents
let ch1 = map fst children ++ map snd children
mutated <- mapM (mutate mute) ch1
return $ map develop mutated
I'm not entirely sure I understand the error and I would think that because both mom
and dad
are of class Phenotype
which means they must support a genome
method this should not be a problem. One problem I can see is that GHC can't make sure that the newly created Genomes will result in the same Phenotypes as it receives, but I'm not sure of how to solve that problem. There also might be some problems with the class declarations that I have overlooked so I would probably help to get someone better than me to look it over.