[Haskell-beginners] Padding List with Zeros
Henry Olders
henry.olders at mcgill.ca
Wed Sep 15 09:15:49 EDT 2010
On 2010-09-14, at 19:35 , Lorenzo Isella 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
Being a real Haskell newby, I can figure out a one-line solution in Python, but I don't know how to do something similar in Haskell, or even if it's possible. Please correct me if I'm wrong, but there does not seem to be a dictionary type in Haskell, and I am not aware of how to specify an inline if...else inside a list comprehension. I would really appreciate it if someone could show me how to do something similar to this Python statement in Haskell.
>>> A=[0,10,20,30,40,50]
>>> B=[0,10,50]
>>> C=[2,1,-5]
>>> [dict(zip(B,C))[a] if a in B else 0 for a in A]
[2, 1, 0, 0, 0, -5]
Henry
More information about the Beginners
mailing list