簡體   English   中英

IO monad 中的明顯冗余調用?

[英]Apparent redundant calls in a IO monad?

這是從 Haskell GPipe 項目中獲取的代碼片段(我自己評論,用“真的嗎?”保存該行)。 memoize function 中,我不明白為什么它的作者第二次調用 getter 來緩存新計算的值。 它對我來說似乎沒有必要,並且可以在沒有明顯不良后果的情況下將其刪除(至少,我的一個中型項目在沒有它的情況下仍然可以工作)。

{- | A map (SN stands for stable name) to cache the results 'a' of computations 'm a'.
The type 'm' ends up being constrained to 'MonadIO m' in the various functions using it.
-}
newtype SNMap m a = SNMap (HT.BasicHashTable (StableName (m a)) a)

newSNMap :: IO (SNMap m a)
newSNMap = SNMap <$> HT.new

memoize :: MonadIO m
    => m (SNMap m a) -- ^ A "IO call" to retrieve our cache.
    -> m a -- ^ The "IO call" to execute and cache the result.
    -> m a -- ^ The result being naturally also returned.
memoize getter m = do
    s <- liftIO $ makeStableName $! m -- Does forcing the evaluation make sense here (since we try to avoid it...)?
    SNMap h <- getter
    x <- liftIO $ HT.lookup h s
    case x of
        Just a -> return a
        Nothing -> do
            a <- m
            SNMap h' <- getter -- Need to redo because of scope. <- Really?
            liftIO $ HT.insert h' s a
            return a

我得到它。 使用的 scope 術語與 Haskell 'do' scope 無關。 很簡單,計算可以在評估時遞歸更新緩存(如在同一模塊中的scopedM function 中......)。 回想起來有點明顯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM