I'm doing a fun side project using Haskell's accelerate library. I have a function that I need to write, which in pure Haskell would look like this:
oddfac :: Int -> Int
oddfac n = product [1,3...n]
i.e. similar to the factorial function, but only multiplying the odd numbers. I'd like to execute this function on the accelerate backend, so if I understand things correctly, it needs to become of type Exp Int -> Exp Int
. However, the library doesn't allow arbitrary expressions to be evaluated in Exp
, for performance reasons. Fortunately, I only ever need to evaluate this function for small values, e.g. n<=7. I had the idea to define a list (or array) of precalculated return values so that simply indexing it would return the appropriate value, and each evaluation would take the same amount of time, which is not the case for the naive version. However, I have not been able to find a way to do this. I now have two questions:
1) Is there a way to do this, i.e. to define a hardcoded array which is then indexed to retrieve the appropriate value within a function of type Exp a -> Exp b
?
2) Am I going about things in an efficient way? Are there any obvious flaws in how I am thinking about this prolem?
UPDATE
The following works, based on @ErikR's answer and subsequent comment:
module Test where
import Data.Array.Accelerate as A
import Prelude as P
oddfac :: Exp Int -> Exp Int
oddfac n = (use $ A.fromList (Z :. 6) [1, 1, 3, 3, 15, 15]) A.! (index1 n)
alloddfac :: Acc (Vector Int)
alloddfac = A.map oddfac $ use $ A.fromList (Z :. 3) [1, 3, 5]
Exp Int
? Then you could do away with lists/indexing altogether.