数日前にこの質問を投稿しました:動的プログラミングを使用した Haskell のパフォーマンスで、文字列の代わりに ByteStrings を使用することをお勧めしました。ByteStrings を使用してアルゴリズムを実装した後、プログラムがクラッシュし、メモリの制限を超えます。
import Control.Monad
import Data.Array.IArray
import qualified Data.ByteString as B
main = do
n <- readLn
pairs <- replicateM n $ do
s1 <- B.getLine
s2 <- B.getLine
return (s1,s2)
mapM_ (print . editDistance) pairs
editDistance :: (B.ByteString, B.ByteString) -> Int
editDistance (s1, s2) = dynamic editDistance' (B.length s1, B.length s2)
where
editDistance' table (i,j)
| min i j == 0 = max i j
| otherwise = min' (table!((i-1),j) + 1) (table!(i,(j-1)) + 1) (table!((i-1),(j-1)) + cost)
where
cost = if B.index s1 (i-1) == B.index s2 (j-1) then 0 else 1
min' a b = min (min a b)
dynamic :: (Array (Int,Int) Int -> (Int,Int) -> Int) -> (Int,Int) -> Int
dynamic compute (xBnd, yBnd) = table!(xBnd,yBnd)
where
table = newTable $ map (\coord -> (coord, compute table coord)) [(x,y) | x<-[0..xBnd], y<-[0..yBnd]]
newTable xs = array ((0,0),fst (last xs)) xs
メモリ消費量は に比例するように見えますn
。入力文字列の長さは 1000 文字です。editDistance
各ソリューションが印刷された後、Haskell が使用されているすべてのメモリを解放することを期待します。そうではありませんか?そうでない場合、どうすればこれを強制できますか?
私が見る唯一の他の実際の計算は for ですcost
が、それを強制してseq
も何もしませんでした。