Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

haskell how to check two lists of tuples are equal and take union

Tags:

list

tuples

I am a new self-leaner in Haskell. firstly, I want to write a function to check if two lists of tuples are equal. Each tuple has a key and value

secondly, I want a function to union two lists of tuples

I tried several ways and tried many times but seems couldn't meet my requirements. could anyone help me? thanks in advance.

like image 999
cynn Avatar asked Oct 08 '18 13:10

cynn


1 Answers

Since a is only a member of Eq, sorting or grouping is not an option.

import Data.List(nub, (\\))
import Data.Monoid(getSum)

type Times = Int
type Lis a = [(a,Times)]

lisEqual :: Eq a => Lis a -> Lis a -> Bool
lisEqual xs xs' = length xs == length xs' && xs \\ xs' == []

lisSum :: Eq a => Lis a-> Lis a-> Lis a
lisSum xs xs' = fmap f $ getKeys l 
  where
    f x = (,) x (getSum . foldMap (pure . snd) . filter ((x ==) . fst) $ l)                         
    l = xs ++ xs'
    getKeys = nub . fst . unzip
like image 81
ƛƛƛ Avatar answered Oct 05 '22 08:10

ƛƛƛ