[Haskell-beginners] Padding List with Zeros

Ozgur Akgun ozgurakgun at gmail.com
Wed Sep 15 06:11:41 EDT 2010


FWIW here is another solution, using only lists. (Whereas I agree with
others who suggested using *proper* data structures rather than 'lists for
everything')

-- walks over both lists, always consumes an element from
-- the first list, consumes an element from the second list
-- only if values are equal.
ix :: Ord a => [a] -> [a] -> [b -> Maybe b]
ix (a:as) (b:bs) | a == b = Just : ix as bs
ix (a:as) (b:bs) | a < b  = const Nothing : ix as (b:bs)
ix _ _ = []

-- consume a value from the second list, only if the current
-- function coming from the first list evaluates to a Just
proj :: [a -> Maybe b] -> [a] -> [Maybe b]
proj [] _ = []
proj (f:fs) (x:xs) =
    let fx  = f x
        nextxs Nothing = x : xs
        nextxs _       = xs
    in  fx : proj fs (nextxs fx)

*Main> proj (ix inp_a inp_b) inp_c
[Just 2,Just 1,Nothing,Nothing,Nothing,Just (-5)]

And of course, if you really want to substitute 0's for Nothings, you can do
it using something like:

to0s :: Num a => [Maybe a] -> [a]
to0s = map (fromMaybe 0)

*Main> to0s $ proj (ix inp_a inp_b) inp_c
[2,1,0,0,0,-5]

Hope this helps,
Ozgur

On 15 September 2010 00:35, Lorenzo Isella <lorenzo.isella at gmail.com> wrote:

> Dear All,
> I still have to find my way with immutable lists and list comprehension.
> Consider the following lists
>
> A=[0,10,20,30,40,50]
> B=[0,10,50] (i.e. B is a subset of list A; list A is already ordered in
> increasing order and so is B).
> C=[2,1,-5] i.e. there is a corresponding element in C for every element in
> B.
>
> Now, I would like to define a new list D having length equal to the length
> of A. The elements of D in the position of the elements of A in common with
> B are equal to the corresponding entries in C, whereas the other ones are
> zero i.e.
> D=[2,1,0,0,0,-5]. How can I achieve that? The first thought that comes to
> my mind is to define a list of zeros which I would modify according to my
> needs, but that is not allowed...
> Many thanks
>
> Lorenzo
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100915/8bddf651/attachment-0001.html


More information about the Beginners mailing list