简体   繁体   中英

Merge two List [“String”,Float] into new list [“String”,Float,Float]

We need to merge both lists into one who takes de number of frequency who a word appears in lists.

If we have:

        `List 1 [("Hi", 0.45),("Steve", 0.0.5),("Bye",0.9)]...`

        `List 2 [("Hello", 0.56), ("Steve", 0.6), ("Bye", 0.6)]..`

we want to get: [("Hi",0.45,0), ("Steve", 0.0.5, 0.6)...

 mergeLists :: [(a,Float)] -> [(a,Float)] -> [(a,Float,Float)]
 mergeLists v y = map (\x -> ( fst x, if not (elem (fst x) v) then 0 
                                        else 5 ,
                                        if not (elem (fst x) v) then 5
                                        else 0))y

Now we are doing by the following code, but we have a lot of problems to continue.

I'm trying to go forward the first list, if list2 doesn't contains the element write 0, otherwise write the frequency value of both lists into the new one.

This is easy when working with sorted lists. You need to augment the usual union function definition in that case, adapting it to your specific data type, like

mergeOrderedLists a b = go a b 
   where go a@((x,n):t) b@((y,m): ..... ) = case compare x y of
                LT -> (x,n,0) : go t b
                EQ -> ....... : go t r 
                GT -> ....... : go a r
         go [] b = ......
         ......

you will have to complete the missing cases here (and for the empty lists too).

You will have to sort each of the argument lists to be able to use this function, to define what you describe.

Is it important to preserve the order of the lists? If not, you can do this with Data.Map . This gives you a map where the key is each word and the value is a [Float] . As a bonus you can combine as many lists this way as you want.

import Control.Arrow (second)

M.fromListWith (++) $ map (second (:[])) $ list1 ++ list2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM