haskell array access

David Roundy droundy@jdj5.mit.edu
Fri, 27 Jun 2003 13:49:03 -0400


On Fri, Jun 27, 2003 at 12:10:55PM -0500, Shawn P. Garbett wrote:
> - --------------------------------------
> New Haskell version with Unboxed Array
> Note:it was a simple change of import and type
> - -----------------------------------------
> import Data.Array.Unboxed
> 
> a :: UArray Int Int
> a =  array (0,15) [(i, i) | i <- [0 .. 15] ]
> 
> acc :: Int -> Int -> Int
> acc s 0  = s
> acc s n  = acc (s + (a ! (n `mod` 16))) (n-1)
> 
> main :: IO ()
> main = do
>          print $ acc 0 100000000

I'd be curious to see timing on the following:

import Data.Array.Unboxed
import Data.Bits

a :: UArray Int Int
a =  array (0,15) [(i, i) | i <- [0 .. 15] ]

acc :: Int -> Int -> Int
acc s 0  = s
acc s n  = acc (s + (a ! (n .&. 15))) (n-1)

main :: IO ()
main = do
         print $ acc 0 100000000

All I've done eliminated the mod call in favor of a bitwise and.  I would
hope that the C compiler would do that, at least if it gives any
improvement.
-- 
David Roundy
http://civet.berkeley.edu/droundy/