【问题标题】:Performance of Conway's Game of Life using the Store comonad使用 Store comonad 执行 Conway 的生命游戏
【发布时间】:2018-01-12 09:25:54
【问题描述】:

我已经使用Store comonad 编写了Conway's Game of Life 的简单实现(参见下面的代码)。我的问题是网格生成从第五次迭代开始明显变慢。我的问题是否与我使用 Store comonad 的事实有关?还是我犯了一个明显的错误?据我所知,other implementations 是基于 Zipper 共轭的,效率很高。

import Control.Comonad

data Store s a = Store (s -> a) s

instance Functor (Store s) where
    fmap f (Store g s) = Store (f . g) s

instance Comonad (Store s) where
    extract (Store f a) = f a
    duplicate (Store f s) = Store (Store f) s

type Pos = (Int, Int)

seed :: Store Pos Bool
seed = Store g (0, 0)
    where
        g ( 0,  1) = True
        g ( 1,  0) = True
        g (-1, -1) = True
        g (-1,  0) = True
        g (-1,  1) = True
        g _        = False

neighbours8 :: [Pos]
neighbours8 = [(x, y) | x <- [-1..1], y <- [-1..1], (x, y) /= (0, 0)]

move :: Store Pos a -> Pos -> Store Pos a
move (Store f (x, y)) (dx, dy) = Store f (x + dx, y + dy)

count :: [Bool] -> Int
count = length . filter id

getNrAliveNeighs :: Store Pos Bool -> Int
getNrAliveNeighs s = count $ fmap (extract . move s) neighbours8

rule :: Store Pos Bool -> Bool
rule s = let n = getNrAliveNeighs s
        in case (extract s) of
            True  -> 2 <= n && n <= 3
            False -> n == 3

blockToStr :: [[Bool]] -> String
blockToStr = unlines . fmap (fmap f)
    where
        f True  = '*'
        f False = '.'

getBlock :: Int -> Store Pos a -> [[a]]
getBlock n store@(Store _ (x, y)) =
    [[extract (move store (dx, dy)) | dy <- yrange] | dx <- xrange]
    where
        yrange = [(x - n)..(y + n)]
        xrange = reverse yrange

example :: IO ()
example = putStrLn
        $ unlines
        $ take 7
        $ fmap (blockToStr . getBlock 5)
        $ iterate (extend rule) seed

【问题讨论】:

    标签: performance haskell comonad


    【解决方案1】:

    store comonad 本身并不真正存储任何东西(除非在抽象意义上,函数是一个“容器”),但必须从头开始计算它。经过几次迭代,这显然变得非常低效。

    如果您只使用 some memoisation 备份 s -&gt; a 函数,您可以在不更改代码的情况下缓解此问题:

    import Data.MemoTrie
    
    instance HasTrie s => Functor (Store s) where
      fmap f (Store g s) = Store (memo $ f . g) s
    
    instance HasTrie s => Comonad (Store s) where
      extract (Store f a) = f a
      duplicate (Store f s) = Store (Store f) s
    

    尚未测试这是否真的提供了可接受的性能。

    顺便说一句,Edward Kmett 有一个明确记忆的版本in an old version of the comonad-extras package,但现在它已经消失了。我最近looked if that still works (在调整依赖项后似乎确实如此)。

    【讨论】:

      猜你喜欢
      • 2013-12-01
      • 2016-04-05
      • 1970-01-01
      • 2023-02-08
      • 2018-07-11
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      相关资源
      最近更新 更多