Skip to content

Commit

Permalink
- Allow built-in classes to be redefined with extra parameters.
Browse files Browse the repository at this point in the history
Must be called with `main::ClassName(...)`.

Example:

    class String(a,b) {

        method to_s {
            "String(#{a.dump}, #{b.dump})"
        }

        method in_blue {
            "#{self} in blue"
        }
    }

    var a = String("foo")                 # calls the String class
    var b = main::String("foo", "bar")    # calls the user-defined class with two parameters

    say a                   #=> foo
    say b.in_blue           #=> String("foo", "bar") in blue
  • Loading branch information
trizen committed Jan 8, 2021
1 parent d71de37 commit bee6726
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
2 changes: 1 addition & 1 deletion lib/Sidef/Parser.pm
Original file line number Diff line number Diff line change
Expand Up @@ -1501,7 +1501,7 @@ package Sidef::Parser {

($name, $class_name) = $self->get_name_and_class($1);

if (exists($self->{built_in_classes}{$name})) {
if (exists($self->{built_in_classes}{$name}) and /\G(?=[{<])/) {

my ($obj) = $self->parse_expr(code => \$name);

Expand Down
24 changes: 21 additions & 3 deletions scripts/Tests/built_in_classes.sf
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class String << Custom {
method in_red {
"#f00 --#{self}--"
}
};
}

"hello".in_red.contains("#f00") || "error -1".die;
"hello".in_blue.contains("in_blue") || "error 0".die;
Expand Down Expand Up @@ -44,5 +44,23 @@ class String {
"hello".in_yellow.contains("#ff0") || "error 2".die;
"hello".in_green.contains("#0f0") || "error 3".die;

# All OK!
say "** Test passed!";
class String(a,b) {

method to_s {
"String(#{a.dump}, #{b.dump})"
}

method in_blue {
"#{self} in blue"
}
}

do {
var obj1 = String("foo") # calls the String class
var obj2 = main::String("foo", "bar") # calls the user-defined class with two parameters

assert_eq(obj1, "foo")
assert_eq(obj2.in_blue, %q<String("foo", "bar") in blue>)
}

say "** Test passed!"
16 changes: 16 additions & 0 deletions scripts/Tests/number_methods.sf
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,20 @@ assert_eq(20.of { .uphi }, 20.of { _ ? .factor_map { |p,e| p**e - 1 }.prod : 0
assert_eq(1..100 -> grep { .is_smooth(5) }, 1..100 -> grep { .gpf <= 5 })
assert_eq(2..100 -> grep { .is_rough(5) }, 2..100 -> grep { .lpf >= 5 })

do {
var a = Math.smooth_numbers(2,3,5,7) # 7-smooth numbers
var b = Math.smooth_numbers(2,5,7) # 7-smooth numbers not divisible by 3

assert_eq(a.first(30), 30.by { .is_smooth(7) })
assert_eq(b.first(30), 30.by {!.is_div(3) && .is_smooth(7) })

# Iteration is also supported
a.each {|k|
if (k > 1e5) {
assert_eq(k, 100352)
break
}
}
}

say "** Tests passed!"

0 comments on commit bee6726

Please sign in to comment.