arrays - 如何从函数创建 Haskell 数组

标签 arrays haskell

出于缓存目的,我想创建一个数组,它将函数的输入值映射到输出值。我知道,我的函数只会在这个特定范围内使用,我想这样的事情:

MyType = ... deriving (Ix)

myFunction :: MyType -> foo

myCache = createArrayFromFunction (start,end) myFunction

这是可能的还是我只是认为“不起作用”并且还有另一种解决方案。我需要数组,因为我需要 O(1) 访问成员并从一开始就知道长度。

最佳答案

如果你只是想创建一个缓存,那么你可以使用 listArraymap ,只要您有所有索引的列表:

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要么,但我可以想象需要它。如果你不在一个模块中,你可以把 myInternalFunclet - 或 where -在 myFuncCache 内阻止.一旦你这样做了,myFunction mt只是进行缓存查找,O(1) 也是如此。

关于arrays - 如何从函数创建 Haskell 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3953414/

相关文章:

c++ - 在没有默认构造函数的类类型的 #define 中初始化大小的非静态成员数组

ruby - 比较数组中多个散列的值

haskell - 一份数据两种结构: Functional Programming vs Imperative Programming

haskell - 将类型作为参数传递给 Haskell 中的函数?

php - 如何在php中展平多维数组

c++ - 存储数组的字符串

c++ - c++中的for循环迭代

haskell - 执行顺序影响 haskell 的空间复杂度

haskell - 函数式解题: how to use Haskell?

haskell - 在 Haskell 中混合 ByteString 解析和网络 IO