On 22 March 2012 00:08, Brandon Allbery <allber...@gmail.com> wrote:

> * + $c --- the next value is the current value plus $c.  ("*" means
> "Whatever", and generally refers to the current value of something.  In this
> case, we're specifying how to make a new value given a current value.  You
> can think of it as a way to make an anonymous function.  In Haskell this
> would be "(+ c)" or "\x -> x + c"; in Python, "lambda x: x + c"; in Perl 5,
> "sub {$_[0] + $c}".  The meaning of * is context dependent, though; when
> accessing array elements, for example, * refers to the end of the array, so
> @arr[* - 1] means the second last element of @arr.)


Interesting... a lambda expression...

> my &add3 = * + 3
WhateverCode.new()
>
> add3(2)
5


Cool... this actually works... But I notice that to use 'add3' in the
list construction I need to put an ampersand:

> 2, &add3 ... 14
2 5 8 11 14


Still... the fact that this works is neat.



> * >= $b --- this determines where the sequence ends:  when the current value
> is greater or equal to $b.


So...  after the "..." you have an anonymous function that has to
return 'True' for the sequence to end? Seems strange, but it works:

# A "function" that always returns True => List of one item.
> 2,5...True
2


So if I want to go from $a to $b by steps of $c, the correct recipe would be:

$a, *+$c ... * >= $b - $c

With this information, I can write something like this:

sub infix:<|>( Range $r, Int $c ) {
    my ($a, $b) = $r.bounds;
    return $a, *+$c ... * >= $b - $c
}

(2..10)|3   == 2, 5, 8

This would look better if I removed the parenthesis, but I'm having
trouble telling Rakudo that this infix operator is looser than the ..
operator:

sub infix:<|>( Range $r, Int $c ) is looser( &infix:<..> ) {
    ...
}
No applicable candidates found to dispatch to for 'trait_mod:<is>'.



> haral:6704 Z$ ./perl6 -e 'say (2, 4 ... 10).^methods'

Thanks. That's very useful.

> The .^ operator runs a method on the object's "metaobject", which determines
> how it associates with its class and roles.  The metaobject is available via
> the HOW method, but is not something you can print or etc.; working with it
> directly is somewhat painful, which is why .^ exists.

Ok.


-- 
I'm not overweight, I'm undertall.

Reply via email to