Updating lists inside another list

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Updating lists inside another list

Aaron MacDonald
I have a list of pairs. Each pair has a value and a list. So, the  
structure looks like this:

[ (a, [b, c]), (b, [a, c]) ]

What I want to do is be able to add an element to the inner list of  
the pair with the head value of my choosing.  So, for the above list:

 > addToInnerList [ (a, [b, c]), (b, [a, c]) ] a d
[ (a, [b, c, d]), (b, [a, c]) ]
Reply | Threaded
Open this post in threaded view
|

Updating lists inside another list

Lee Duhem
On Tue, Jun 23, 2009 at 8:05 AM, Aaron MacDonald<[hidden email]> wrote:

> I have a list of pairs. Each pair has a value and a list. So, the structure
> looks like this:
>
> [ (a, [b, c]), (b, [a, c]) ]
>
> What I want to do is be able to add an element to the inner list of the pair
> with the head value of my choosing. ?So, for the above list:
>
>> addToInnerList [ (a, [b, c]), (b, [a, c]) ] a d
> [ (a, [b, c, d]), (b, [a, c]) ]
> _______________________________________________

A simple recursive definition will do this:

addToInnerList [] _ _ = []
addToInnerList (x@(h,l):xs) a b
    | h == a = (h,l++[b]):xs
    | otherwise = x : addToInnerList xs a b

BTW, is it your homework?

lee
Reply | Threaded
Open this post in threaded view
|

Updating lists inside another list

Lee Duhem
On Tue, Jun 23, 2009 at 11:29 AM, Joel Neely<[hidden email]> wrote:
> WRT the first case, I would have expected something like;
>
> addToInnerList [] a b = [(a,[b])]
>
> on the assumption that one "grows" a structure from an empty state.
> Your thoughts?
>

I think it isn't what Aaron wants, that is "to add an element to the
inner list of
the pair with the head value of my choosing".

Anyway, it is an option.

lee