How to create a Haskell array from a function

For caching purposes, I want to create an array that displays the input values ​​of a function to output values. I know that my function will be used only in this specific range, I am thinking of something like this:

MyType = ... deriving (Ix)

myFunction :: MyType -> foo

myCache = createArrayFromFunction (start,end) myFunction

Is this possible, or I just think that “doesn't work” is another solution. I need arrays because I need O (1) access to members and know the length from the start.

+5
source share
2 answers

If you just want to create a cache, you can just use listArrayand mapif you have a list of all your indexes:

myCache :: Array MyType Foo
myCache = listArray (start,end) . map myFunction $ range (start,end)

, 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 !)

myInternalFunc ; , , myFuncCache, , . , myInternalFunc let - where -block myFuncCache. , myFunction mt , O (1).

+6

, Vector. , , , , Int. , :

generate :: Int -> (Int -> a) -> Vector a
+3

All Articles