我正在写一个遗传算法来生成字符串“helloworld”。但是当n为10,000或更多时,evolve函数会产生堆栈溢出。哈斯克尔堆栈溢出
module Genetics where
import Data.List (sortBy)
import Random (randomRIO)
import Control.Monad (foldM)
class Gene g where
-- How ideal is the gene from 0.0 to 1.0?
fitness :: g -> Float
-- How does a gene mutate?
mutate :: g -> IO g
-- How many species will be explored?
species :: [g] -> Int
orderFitness :: (Gene g) => [g] -> [g]
orderFitness = reverse . sortBy (\a b -> compare (fitness a) (fitness b))
compete :: (Gene g) => [g] -> IO [g]
compete pool = do
let s = species pool
variants <- (mapM (mapM mutate) . map (replicate s)) pool
let pool' = (map head . map orderFitness) variants
return pool'
evolve :: (Gene g) => Int -> [g] -> IO [g]
evolve 0 pool = return pool
evolve n pool = do
pool' <- compete pool
evolve (n - 1) pool'
随着species pool = 8
,8个基因池复制到8组。每组进行变异,并选择适合每个组进行进一步进化(回到8个基因)。
假设你正在使用'GHC -O2'为你的编译器,你的第一个版本没有在'evolve'功能的堆栈溢出。由于我们看不到“竞争”的实施,这就是可以说的。 – 2011-05-10 21:25:19
上面提供的GitHub链接(https://github.com/mcandre/genetics)指定了“竞争”以及确实使用'ghc -O2'的Makefile。我认为第一个例子中的<-'足以防止堆栈溢出。我不确定问题出在哪里。 – mcandre 2011-05-10 21:32:37
>> =应该等于符号,那里没有区别。 – alternative 2011-05-10 21:36:12