出于缓存目的,我想创建一个数组,它将函数的输入值映射到输出值。我知道,我的函数只会在这个特定范围内使用,我想这样的事情:
MyType = ... deriving (Ix)
myFunction :: MyType -> foo
myCache = createArrayFromFunction (start,end) myFunction
这是可能的还是我只是认为“不起作用”并且还有另一种解决方案。我需要数组,因为我需要 O(1) 访问成员并从一开始就知道长度。
最佳答案
如果你只是想创建一个缓存,那么你可以使用 listArray
和 map
,只要您有所有索引的列表:
myCache :: Array MyType Foo
myCache = listArray (start,end) . map myFunction $ range (start,end)
我假设
MyType
有一个 Enum
这里的例子;如果没有,您将需要其他方法来生成有效输入列表,这取决于您的类型。正如 Reid Barton 所指出的,这就是 range
是为了。如果您想向用户展示功能,另一种选择是
myInternalFunc :: MyType -> Foo
myInternalFunc mt = (complex calculation) (using mt)
myFuncCache :: Array MyType Foo
myFuncCache = listArray (start,end) . map myFunction $ range (start,end)
myFunction :: MyType -> Foo
myFunction = (myFuncCache !)
那你就不会导出
myInternalFunc
从你的模块;你可能不会导出 myFuncCache
要么,但我可以想象需要它。如果你不在一个模块中,你可以把 myInternalFunc
在 let
- 或 where
-在 myFuncCache
内阻止.一旦你这样做了,myFunction mt
只是进行缓存查找,O(1) 也是如此。
关于arrays - 如何从函数创建 Haskell 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3953414/