[Haskell-beginners] Re: Padding List with Zeros

Ertugrul Soeylemez es at ertes.de
Tue Sep 14 20:34:28 EDT 2010

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...

Here is a simple approach using Data.Map:

  import qualified Data.Map as M

  substSubset :: (Num b, Ord a) => [a] -> [b] -> [a] -> [b]
	substSubset ys zs =
    map (\x -> M.findWithDefault 0 x (M.fromList $ zip ys zs))

First build a map from [0, 10, 50] to [2, 1, -5], then map a function
over [0, 10 .. 50], which tries to find each corresponding number in the
map with a default of 0.

But do you really need zero values?  If your zeroes actually represent
lack of a value, consider using Maybe instead:

  [Just 2, Just 1, Nothing, Nothing, Nothing, Just (-5)]

instead of:

  [2, 1, 0, 0, 0, -5]


nightmare = unsafePerformIO (getWrongWife >>= sex)

More information about the Beginners mailing list