[Haskell-beginners] Again on list manipulations
daniel.is.fischer at web.de
Fri Sep 10 11:15:05 EDT 2010
On Friday 10 September 2010 16:55:43, Lorenzo Isella wrote:
> Dear All,
> I know this must be a one-liner, but it am banging my head against the
> wall. I am trying my hands at list manipulation in Haskell and a lot of
> useful function are making my life easier but I cannot achieve something
> really simple.
> Let us say you have the lists ml and sel
> sel=[1,2] .
> Now, I would like simply to get a new list whose entries are the
> elements of ml in position sel.
Simple but potentially very inefficient:
map (ml !!) sel
map (genericIndex ml) sel
As long as all elements of sel are small, that's okay, but imagine
sel = [k*10^6 | k <- [1 .. 10]]
sel = [10^6 + k | k <- [0, 3 .. 1000]]
If sel is increasing,
selection :: Integral a => [a] -> [b] -> [b]
selection sel = pick distances
distances = zipWith (-) sel (0:sel)
pick  _ = 
pick (d:ds) xs = case genericDrop d xs of
 -> 
ys@(y:_) -> y : pick ds ys
*Select> selection [1,1,7,9,12,12,20] [0 .. 16]
*Select> selection [1,1,7,9,12,12,20] [0 .. 1000]
If sel is not increasing, an efficient solution is more complex.
> In my case things might be a little more
> complicated because all the elements are Integer and not Int (I noticed
> that sometimes this means I have to resort to generic functions).
More information about the Beginners