【发布时间】:2015-08-09 20:51:32
【问题描述】:
我正在使用Data.MemoCombinators (https://hackage.haskell.org/package/data-memocombinators-0.3/docs/Data-MemoCombinators.html) 来记忆一个函数,该函数将一个集合作为其参数并返回一个集合(这是一个人为的示例,它什么都不做,但需要很长时间才能完成):
test s = case Set.toList s of
[] -> Set.singleton 0
[x] -> Set.singleton 1
(x:xs) -> test (Set.singleton x) `Set.union` test (Set.fromList xs)
由于Data.MemoCombinators 没有实现集合表,我想自己写:
{-# LANGUAGE RankNTypes #-}
import Data.MemoCombinators (Memo)
import qualified Data.MemoCombinators as Memo
import Data.Set (Set)
import qualified Data.Set as Set
set :: Ord a => Memo a -> ((Set a) -> r) -> (Set a) -> r
set m f = Memo.list m (f . Set.fromList) . Set.toList
这是我应该记住的test:
test s = set Memo.integral test' s
where
test' s = case Set.toList s of
[] -> Set.singleton 0
[x] -> Set.singleton 1
(x:xs) -> test (Set.singleton x) `Set.union` test (Set.fromList xs)
没有我清楚的Data.MemoCombinators 的文档,所以基本上我不知道我在做什么。
我的问题是:
Memo.list函数的第二个参数是什么?它是列表元素的记忆器吗?如何在不使用
Memo.list的情况下直接为一个集合实现一个表?这里想弄清楚如何在不使用某人的库的情况下手动实现记忆。例如,使用Map。我已经看到了使用无限列表来记忆整数的示例,但是在地图的情况下,我无法弄清楚如何初始化地图以及如何将其插入。
感谢您的帮助。
【问题讨论】:
标签: haskell memoization