haskell - Compare two List sorted -


i have codec but, shows no repeated elements, why?

cosinesim :: ord => [(a,float)] -> [(a,float)] -> [(a,float,float)] cosinesim b = go b            go [] b = map (\l -> (fst l, 0, snd l)) b        go [] = map (\l -> (fst l, snd l, 0))        go a@((x,n):t) b@((y,m):r) = case compare x y of            lt -> (x,n,0) : go t b            eq -> (x,n,m) : go t r            gt -> (y,0,m) : go r 

input : 2 list sorted.

list1= [(["variety"], 4.50),(["vegetable"], 3.50),(["velvet"], 2.50)]

list2= [(["variety"], 4.50),(["ve"], 3.50),(["velvet"], 2.50)]

output :

[(["variety"], 4.50, 4.50 ), (["vegetable"], 3.50, 0), (["velvet"], 2.50 2.50) ,(["ve"], 0, 3.50)]

my question because show element repeat in 2 list, because want elements appear.

since want combine elements of both lists, keeping keys unique recommend using map data.map. can combine 2 maps using union, unionwith, or unionwithkey. second 1 more useful here, though. since want indicate when value first or second list using 0, better have data type represents explicitly:

import qualified data.map m  data b     =        -- left     | b     -- both     | b        -- right     deriving (eq, show)  :: -> b -> def (this a)    = def (those b) = def _           = def  :: b -> b -> b def (that b)    = b def (those b) = b def _           = def  -- give better name items type items k = m.map k (those float float) 

this sets couple types , tools we'll use later. those type represents left, right, or both, , this , that combinators extract values them easily, maybe combinator in prelude.

listtoleftitems :: ord => [(a, float)] -> items listtoleftitems = m.fromlist . map (fmap this)  listtorightitems :: ord => [(a, float)] -> items listtorightitems = m.fromlist . map (fmap that)  cosinesim :: ord => [(a, float)] -> [(a, float)] -> [(a, float, float)] cosinesim left right     = map (\(key, those) -> (key, 0 those, 0 those))     $ m.tolist     $ m.unionwith go (listtoleftitems left)                      (listtorightitems right)             go leftval rightval = case (leftval, rightval) of             (this a, b) -> b             (x, y) -> y  -- know won't have other combinations,                          -- keeps compiler throwing warning 

the listtoleftitems applies this every float in list, converts map, , listtorightitems. function converts input lists maps, unions them using go (which think simple enough understand), converts list, flattens out (a, float float) (a, float, float). gives results want, not in same order. can use basis getting in order want, if matters.


Comments