[Haskell-beginners] Again on list manipulations
Daniel Fischer
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
>
> ml=[23,44,55,8,98]
> and
> 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
resp.
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]]
or worse,
sel = [10^6 + k | k <- [0, 3 .. 1000]]
If sel is increasing,
selection :: Integral a => [a] -> [b] -> [b]
selection sel = pick distances
where
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]
[1,1,7,9,12,12]
*Select> selection [1,1,7,9,12,12,20] [0 .. 1000]
[1,1,7,9,12,12,20]
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).
> Cheers
>
> Lorenzo
More information about the Beginners
mailing list