Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two lists of rules?

I need to compare two Lists of Rules of form var -> integer on the fact of mismatch.
To determine, if there are any rules the same by lhs and different by rhs.

For example:

{a->3, b->1, c->4} ~ ??? ~ {a->3, b->1, c->4} = true
{a->3, b->1, c->4} ~ ??? ~ {a->3, b->2, c->4} = false
{a->3, b->1, c->4} ~ ??? ~ {a->1, b->3, c->4} = false
{a->3, b->1, c->4} ~ ??? ~ {c->4, d->8, e->9} = true
{a->3, b->1, c->4} ~ ??? ~ {d->8, e->9, f->7} = true

In my case they are already sorted by lhs and all lhs are unique if it could help to make as simple function as possible.

UPD: forgot one thing! Lists can be of different length. But seems like all three current answers are still valid.

like image 783
Nakilon Avatar asked Oct 11 '11 11:10

Nakilon


2 Answers

Here's another solution:

In[12]:= check[a:{__Rule}, b:{__Rule}] := FilterRules[a, b] === FilterRules[b, a]

In[18]:= {{a -> 3, b -> 1, c -> 4}~check ~ {a -> 3, b -> 1, c -> 4} ,
 {a -> 3, b -> 1, c -> 4}~check ~ {a -> 3, b -> 2, c -> 4},
 {a -> 3, b -> 1, c -> 4}~check ~ {a -> 1, b -> 3, c -> 4},
 {a -> 3, b -> 1, c -> 4}~check ~ {c -> 4, d -> 8, e -> 9},
 {a -> 3, b -> 1, c -> 4}~check ~ {d -> 8, e -> 9, f -> 7}}

Out[18]= {True, False, False, True, True}

(This relies on the fact that the lists of options are already sorted.)

like image 59
Brett Champion Avatar answered Sep 20 '22 02:09

Brett Champion


You could do something like

check[{a__Rule}, {b__Rule}] := 
 Module[{common = Intersection[{a}[[All, 1]], {b}[[All, 1]]]},
  SameQ[common /. {a}, common /. {b}]]

Then

check[{a -> 3, b -> 1, c -> 4}, {a -> 3, b -> 1, c -> 4}]
check[{a -> 3, b -> 1, c -> 4}, {a -> 3, b -> 2, c -> 4}]
check[{a -> 3, b -> 1, c -> 4}, {a -> 1, b -> 3, c -> 4}]

yields

True
False
False
like image 21
Heike Avatar answered Sep 22 '22 02:09

Heike