如何从函数创建Haskell数组

fuz*_*fuz 5 arrays haskell

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

MyType = ... deriving (Ix)

myFunction :: MyType -> foo

myCache = createArrayFromFunction (start,end) myFunction
Run Code Online (Sandbox Code Playgroud)

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

Ant*_*sky 6

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

myCache :: Array MyType Foo
myCache = listArray (start,end) . map myFunction $ range (start,end)
Run Code Online (Sandbox Code Playgroud)

我假设这里MyType有一个Enum实例; 如果没有,您将需要一些其他方法来生成有效输入列表,这取决于您的类型. 正如里德巴顿指出的那样,这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 !)
Run Code Online (Sandbox Code Playgroud)

然后你不会myInternalFunc从你的模块导出; 你可能也不会出口myFuncCache,但我可以想象需要它.如果您不在模块中,则可以myInternalFunc在其中放入let- 或where- 块myFuncCache.执行此操作后,myFunction mt只需执行缓存查找,O(1)也是如此.