For caching purposes, I want to create an array, which maps input values of the function to output values. I know, that my function will be used only in this specific range, I think about something like this:
MyType = ... deriving (Ix)
myFunction :: MyType -> foo
myCache = createArrayFromFunction (start,end) myFunction
Is this possible or do I just think “not functional” and there is another solution. I need arrays, because I need O(1) access to the members and know the length from the beginning.
If you just want to create a cache, then you can just use
listArrayandmap, as long as you have a list of all your indices:I assumed thatAs Reid Barton pointed out, this is whatMyTypehas anEnuminstance here; if it doesn’t, you’ll need some other way to generate a list of valid inputs, which depends on your type.rangeis for.Another option, if you want to present a function to the user, would be
Then you wouldn’t export
myInternalFuncfrom your module; you probably wouldn’t exportmyFuncCacheeither, but I could imagine needing it. If you aren’t in a module, you could putmyInternalFuncin alet– orwhere-block withinmyFuncCache. Once you do this,myFunction mtjust does a cache lookup, and so is O(1).