我試圖創建一個簡單的Haskell進化算法,我試圖使它儘可能通用GHC投訴。這原本是我在Python中解決的一個任務,當我有更多時間並在Haskell中解決時,我想回到這個任務。該任務需要的代碼非常靈活,我試圖在我的初步Haskell實現中重新創建。無法理解歧義
在下面的代碼,你可以看到錯誤GHC是給我:
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
我有下面的類聲明:
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
的代碼是給我的問題是:
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
我不能完全肯定我理解的錯誤,我會認爲,因爲這兩個mom
和dad
是Phenotype
類的,這意味着他們必須支持genome
方法這不應該是一個問題。我可以看到的一個問題是,GHC不能確保新創建的基因組會產生與它接收的相同的表型,但我不知道如何解決這個問題。我忽略了類聲明也可能存在一些問題,所以我可能會幫助讓某人比我更好地查看它。
問題從源頭根源在於調用品種功能。從哪裏調用品種函數的'b'類型是什麼? – mhitza
@mhitza如果我理解正確,源文件中'b'的類型也應該只是類表型。完整的代碼在這裏http://hpaste.org/85037 – Nordmoen