[Haskell-cafe] iota

Paul Keir pkeir at dcs.gla.ac.uk
Mon Jun 1 05:00:39 EDT 2009


Hi all,

 

I was looking for an APL-style "iota" function for array indices. I
noticed

"range" from Data.Ix which, with a zero for the lower bound (here
(0,0)),

gives the values I need:

 

> let (a,b) = (2,3)

> index ((0,0),(a-1,b-1))

> [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2)]

 

However, I need the results as a list of lists rather than a list of
tuples; and

my input is a list of integral values. I ended up writing the following
function

instead. The function isn't long, but longer than I first expected. Did
I miss a

simpler approach?

 

iota :: (Integral a) => [a] -> [[a]]

iota is = let count = product is

                       tups = zip (tail $ scanr (*) 1 is) is

                       buildRepList (r,i) = genericTake count $ cycle $

                                                               [0..i-1]
>>= genericReplicate r

                       lists = map buildRepList tups

                 in transpose lists

 

> length $ iota [2,3,4]

> 24

 

Thanks,

Paul

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090601/8d0b311f/attachment.html


More information about the Haskell-Cafe mailing list