4
下面的函数search
搜索两个在某些函数下具有相同输出的输入。在搜索期间,它重复输入列表xs
两次,并且这个输入列表可能非常大,例如, [0..1000000000]
。我宁愿使用内存来存储由碰撞创建的HashSet,而不是存储xs
的元素,我的理解是,尽管xs
可能会被延迟计算,但它将保留在需要调用find
的情况下。强制重新列表重新计算
问题:
- 是这样理解是否正确?
- 如果我把它作为一个列表有没有一种方法,我可以
xs
重新计算,如果它传递给find
? - 是否有替代的数据结构我可以用于
xs
,它允许我控制使用的空间?xs
仅用于指定要检查的输入。
请注意,xs
没有类型限制 - 它可以是任何类型的集合。
import Data.HashSet as Set
import Data.Hashable
import Data.List
search :: (Hashable b, Eq b) => (a->b) -> [a] -> Maybe (a,a)
search h xs =
do x0 <- collision h xs
let h0 = h x0
x1 <- find (\x -> (h x) == h0) xs
return (x0,x1)
collision :: (Hashable b, Eq b) => (a->b) -> [a] -> Maybe a
collision h xs = go Set.empty xs
where
go s [] = Nothing
go s (x:xs) =
if y `Set.member` s
then Just x
else go (Set.insert y s) xs
where y = h x
main = print $ search (\x -> x `mod` 21) ([10,20..2100] :: [Int])
你真的是指''x1 < - find(\ x - >(h x)'Set.member' s)xs''而不是'h x == h0'? –
很好的捕捉 - 这简单很多 – ErikR
您可以在[美丽折叠](http://squing.blogspot.com/2008/11/beautiful-folding.html)中调整想法以产生漂亮的扫描效果。 –