簡體   English   中英

比較兩個列表排序

[英]Compare two List sorted

我有這個編解碼器,但是它沒有顯示重復的元素,為什么?

cosinesim :: Ord a => [(a,Float)] -> [(a,Float)] -> [(a,Float,Float)]
cosinesim a b = go a b
    where
       go [] b = map (\l -> (fst l, 0, snd l)) b
       go a [] = map (\l -> (fst l, snd l, 0)) a
       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 a r

輸入:兩個列表排序。

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

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

輸出:

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

我的問題是因為僅在兩個列表中顯示重復的元素,因為我要的是所有元素都出現。

由於要合並兩個列表的元素,因此保持鍵的唯一性,我建議使用Data.MapMap 然后,您可以使用unionunionWithunionWithKey合並兩個地圖。 不過,第二個在這里會更有用。 由於您還想僅使用0來指示何時來自第一個列表或第二個列表的0 ,因此最好使用一種明確表示該值的數據類型:

import qualified Data.Map as M

data Those a b
    = This a        -- Only left
    | Those a b     -- Both
    | That b        -- Only right
    deriving (Eq, Show)

this :: a -> Those a b -> a
this def (This a)    = a
this def (Those a b) = a
this def _           = def

that :: b -> Those a b -> b
that def (That b)    = b
that def (Those a b) = b
that def _           = def

-- Give this a better name than Items
type Items k = M.Map k (Those Float Float)

這只是設置了一些類型和工具,我們將在以后使用。 Those類型代表左,右,或兩者兼而有之,而thisthat組合程序幫助我們從中提取值很容易,就像maybe在Combinator的Prelude

listToLeftItems :: Ord a => [(a, Float)] -> Items a
listToLeftItems = M.fromList . map (fmap This)

listToRightItems :: Ord a => [(a, Float)] -> Items a
listToRightItems = M.fromList . map (fmap That)

cosinesim :: Ord a => [(a, Float)] -> [(a, Float)] -> [(a, Float, Float)]
cosinesim left right
    = map (\(key, those) -> (key, this 0 those, that 0 those))
    $ M.toList
    $ M.unionWith go (listToLeftItems left)
                     (listToRightItems right)
    where
        go leftVal rightVal = case (leftVal, rightVal) of
            (This a, That b) -> Those a b
            (x, y) -> y  -- We know we won't have any other combinations,
                         -- this just keeps the compiler from throwing a warning

listToLeftItemsThis到列表中的每個Float ,然后將其轉換為Map ,類似地,將其轉換為listToRightItems 現在,您的函數只需將輸入列表轉換為Map ,使用go合並它們(我認為這很容易理解),轉換回列表,然后將(a, Those Float Float)(a, Float, Float) 它為您提供所需的結果,但順序不同。 如果重要的話,您可以以此為基礎以所需順序獲得它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM