Similarity test between objects
Hi, I've used this function for testing two objects similar or not. May be useful for someone else. similar?: func [o [object!] p [object!]] [ equal? first o first p ] o: context [a: 1 b: 2 c: 3] p: context [a: 1 b: 2 c: 3] same? o p ;== false similar? o p ;== true o: context [a: 1 b: 2 c: 3] p: context [a: 1 b: 2 x: 3] k: context [a: 1 b: 2 c: 3 d: 4] similar? o p ;== false similar? o k ;== false
posted by: Endo 3-Aug-2010/10:19:30-7:00
Here is a better version of SIMILAR? function: This function check two objects have same words and those values are in same types (order of words is not important): similar?: func [o [object!] p [object!]] [ foreach word sort first p [if not equal? type? get in o word type? get in p word [return false] true] ] Here is a quick test what it does: o: context [a: 0 e: does ["y"] b: 4] p: context [e: does ["x"] b: 12 a: 2] similar? o p == true o: context [a: 0 e: does ["y"] b: 4.5] p: context [e: does ["x"] b: 12 a: 2] similar? o p == false (b is decimal in O but integer in P o: context [a: 0 e: does ["y"] b: 4.5] p: context [e: does ["x"] a: 2] similar? o p == false (there is no B in P)
posted by: Endo 4-Nov-2010/11:44:31-7:00
Minor fix, now it test both objects: similar?: func [o [object!] p [object!]] [ foreach word sort first o [if not equal? type? get in o word type? get in p word [return false]] foreach word sort first p [if not equal? type? get in o word type? get in p word [return false]] true ]
posted by: Endo 4-Nov-2010/11:49:17-7:00
Endo, it would be great to add all your functions and short examples to rebol.org.
posted by: Nick 7-Nov-2010/4:14:41-8:00
Thank you Nick, I'll. Here is a little bit better version, it traverse just one object and doesn't check the 'self word (there is always 'self word in all objects) similar?: func [o [object!] p [object!]] [ if not-equal? length? first o length? first p [return false] foreach word next first o [if not equal? type? get in o word type? get in p word [return false]] true ]
posted by: Endo 8-Nov-2010/18:09:31-8:00
|