Skip to content

Commit

Permalink
- Changed slightly the behavior of the smartmatch operator (~~)
Browse files Browse the repository at this point in the history
[1,2] ~~ [1,2,3];  # true; all elements from the first array exists in the second array
  • Loading branch information
trizen committed Jul 2, 2015
1 parent 5108fe7 commit b1d44e1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 19 deletions.
8 changes: 4 additions & 4 deletions lib/Sidef/Object/Object.pm
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ package Sidef::Object::Object {

# Array ~~ Array
if ($s_type eq 'Sidef::Types::Array::Array') {
return $first->contains_all($second);
return $second->contains_all($first);
}

# Array ~~ Regex
Expand All @@ -99,7 +99,7 @@ package Sidef::Object::Object {

# Array ~~ Hash
if ($s_type eq 'Sidef::Types::Hash::Hash') {
return $second->keys->contains_any($first);
return $second->keys->contains_all($first);
}

# Array ~~ Any
Expand All @@ -111,12 +111,12 @@ package Sidef::Object::Object {

# Hash ~~ Array
if ($s_type eq 'Sidef::Types::Array::Array') {
return $first->keys->contains_all($second);
return $second->contains_all($first->keys);
}

# Hash ~~ Hash
if ($s_type eq 'Sidef::Types::Hash::Hash') {
return $first->keys->contains_all($second->keys);
return $second->keys->contains_all($first->keys);
}

# Hash ~~ Any
Expand Down
46 changes: 31 additions & 15 deletions scripts/smart_match_operator.sf
Original file line number Diff line number Diff line change
Expand Up @@ -13,49 +13,65 @@ var array = <red blue green>;
#
if (array ~~ hash) {
say "some array elements in hash keys";
} else {
"a ~~ h error".die;
}
else {
die "a ~~ h error";
}

#
## Any ~~ Array
#
if ("red" ~~ array) {
say "red in array";
} else {
"s ~~ a error".die;
}
else {
die "s ~~ a error";
}

#
## Regex ~~ Hash
#
if (/e$/ ~~ hash) {
say "some keys end in e";
} else {
"r ~~ h error".die;
}
else {
die "r ~~ h error";
}

#
## Hash ~~ Hash
#
var sub_h = :(red => 5, :white => 1);
if (hash ~~ sub_h) {
if (sub_h ~~ hash) {
say "sub-hash contained in larger hash";
} else {
"h ~~ h error".die;
}
else {
die "h ~~ h error";
}

#
## Hash ~~ Array
#

if (:(a => 1, b => 2) ~~ ["a", "b", "c"]) {
say "all hash-keys contained in array";
}
else {
die "h ~~ a error";
}

#
## Array ~~ Array
#
var arr1 = [1,2,3];
var arr2 = [3,2];
var arr1 = [3,2];
var arr2 = [1,2,3];

if (arr1 ~~ arr2) {
say "sub-array contained in larger array";
} else {
"a ~~ a error".die;
}
else {
die "a ~~ a error";
}

arr2.append(0);
arr1 ~~ arr2 && "a ~~ a error(2)".die;
arr1.append(0);
arr1 ~~ arr2 && die "a ~~ a error(2)";

0 comments on commit b1d44e1

Please sign in to comment.