[Haskell-cafe] generic sum for an UArr

Daniel Fischer daniel.is.fischer at web.de
Wed Mar 11 18:27:10 EDT 2009


Am Mittwoch, 11. März 2009 23:13 schrieb Manlio Perillo:
> Hi.
>
> I have an array (Data.Array.Vector.UArr) of Word8 elements.
> Elements are stored as Word8 to keep memory usage down.
>
> Now I need to compute the sum of all the array elements; what is the
> best method?
> The sum must be of type Int.
>
>
> How efficient is to simply convert to an UArr Int, using:
>
>    mapU fromIntegral v :: UArr Int
> ?
>
>
> What about, instead, of something like:
>
>    genericSumU :: (UA e, Integral e) => UArr e -> Int
>    genericSumU = foldU add 0

That would have to be foldlU, the type of foldU is
foldU :: UA a => (a -> a -> a) -> a -> UArr a -> a

while 
foldlU :: UA a => (b -> a -> b) -> b -> UArr a -> b

>        where
>          add x y = x + fromIntegral y
> ?
>
>
> Unfortunately the latter does not compile:
>
>   Couldn't match expected type `Int' against inferred type `e'
>        `e' is a rigid type variable bound by
>            the type signature for `genericSumU' at
> bin/process-data-1.hs:64:19
>      In the expression: foldU add 0
>      In the definition of `genericSumU':
>          genericSumU = foldU add 0
>                      where
>                          add x y = x + fromIntegral y
>
>
> Moreover, this is not really a generic version.
> I would like to have:
>
>    genericSumU :: (Num i, UA e, Num e) => UArr e -> i
>
> is this possible?
>
>
>
> Thanks  Manlio
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe



More information about the Haskell-Cafe mailing list