Access callee/this in Raku map code/block - raku

Is it possible to access the "callee" ("this") in Raku map code block and/or whatevercode?
E.g. if one wanted to calculate arithmetic mean
my $data = <1 10 0 7 2> ;
say $data.sum
/ $data ; # or #$data, same as $data.elems in this numeric context
# OUTPUT: «4␤»
by sum of fractions
say $data.map(* / $data).sum
# OUTPUT: «4␤»
like
<1 10 0 7 2>.map({ $_ / $this }).sum # but there's no $this
or
<1 10 0 7 2>.map( * / $this ).sum
If not, is there an idiomatic way to do it with only a chain of method calls on the <…> data literal, or different way, without storing the data in variable?

There is not, to my knowledge. You would need to be able to know how many values an iterator will produce.
Under the hood, a foo.map: &callable is basically a:
my $iterator = foo.iterator;
callable($iterator.pull-one) until iterator exhausted;
Note that all knowledge of the source of the iterator is lost at that point: there's just an iterator producing values.
Some types of iterators (the so-called PredictiveIterators can tell you how many values it can still produce without actually producing them. But most iterators are not able to do that.
I guess technically it would be possible for map to check whether it got a PredictiveIterator and set a dynamic variable with the number of values it will produce, which you could then check inside the &callable.
Still, it doesn't feel that this is worth the extra check for all maps and for loops, so I don't think a PR for such a feature would be accepted.

you could do this, by andthen
<1 10 0 7 2>
andthen .sum / .elems
andthen .say
or
<1 10 0 7 2>
andthen .map: * / .elems
andthen .sum
andthen .say

As Liz mentioned, there's no variable that's auto-bound to the value being iterated over, but there are several ways to do what you want. Here are three ways to do so by binding the series to the topic variable (the first is most concise and is probably what I'd write):
<1 10 0 7 2>.&{ .map(* / $_).sum };
given <1 10 0 7 2> { .map(* / $_).sum };
with <1 10 0 7 2> { .map(* / $_).sum };
Another option would be to duplicate the initial list with xx. Here's one way that could look, though I'm not huge fan of it in this case.
(<1 10 0 7 2> xx 2).map({|$^a.map: * / $_}).sum;
Similarly, you could zip each element with the list as a whole (which would be overkill in this simple case, but might be useful in similar situations.)

Related

How to generate a lazy division?

I want to generate the sequence of
1, 1/2, 1/3, 1/4 ... *
using functional programming approach in raku, in my head it's should be look like:
(1,{1/$_} ...*)[0..5]
but the the output is: 1,1,1,1,1
The idea is simple, but seems enough powerful for me to using to generate for other complex list and work with it.
Others things that i tried are using a lazy list to call inside other lazy list, it doesn't work either, because the output is a repetitive sequence: 1, 0.5, 1, 0.5 ...
my list = 0 ... *;
(1, {1/#list[$_]} ...*)[0..5]
See #wamba's wonderful answer for solutions to the question in your title. They showcase a wide range of applicable Raku constructs.
This answer focuses on Raku's sequence operator (...), and the details in the body of your question, explaining what went wrong in your attempts, and explaining some working sequences.
TL;DR
The value of the Nth term is 1 / N.
# Generator ignoring prior terms, incrementing an N stored in the generator:
{ 1 / ++$ } ... * # idiomatic
{ state $N; $N++; 1 / $N } ... * # longhand
# Generator extracting denominator from prior term and adding 1 to get N:
1/1, 1/2, 1/3, 1/(*.denominator+1) ... * # idiomatic (#jjmerelo++)
1/1, 1/2, 1/3, {1/(.denominator+1)} ... * # longhand (#user0721090601++)
What's wrong with {1/$_}?
1, 1/2, 1/3, 1/4 ... *
What is the value of the Nth term? It's 1/N.
1, {1/$_} ...*
What is the value of the Nth term? It's 1/$_.
$_ is a generic parameter/argument/operand analogous to the English pronoun "it".
Is it set to N?
No.
So your generator (lambda/function) doesn't encode the sequence you're trying to reproduce.
What is $_ set to?
Within a function, $_ is bound either to (Any), or to an argument passed to the function.
If a function explicitly specifies its parameters (a "parameter" specifies an argument that a function expects to receive; this is distinct from the argument that a function actually ends up getting for any given call), then $_ is bound, or not bound, per that specification.
If a function does not explicitly specify its parameters -- and yours doesn't -- then $_ is bound to the argument, if any, that is passed as part of the call of the function.
For a generator function, any value(s) passed as arguments are values of preceding terms in the sequence.
Given that your generator doesn't explicitly specify its parameters, the immediately prior term, if any, is passed and bound to $_.
In the first call of your generator, when 1/$_ gets evaluated, the $_ is bound to the 1 from the first term. So the second term is 1/1, i.e. 1.
Thus the second call, producing the third term, has the same result. So you get an infinite sequence of 1s.
What's wrong with {1/#list[$_+1]}?
For your last example you presumably meant:
my #list = 0 ... *;
(1, {1/#list[$_+1]} ...*)[0..5]
In this case the first call of the generator returns 1/#list[1+1] which is 1/2 (0.5).
So the second call is 1/#list[0.5+1]. This specifies a fractional index into #list, asking for the 1.5th element. Indexes into standard Positionals are rounded down to the nearest integer. So 1.5 is rounded down to 1. And #list[1] evaluates to 1. So the value returned by the second call of the generator is back to 1.
Thus the sequence alternates between 1 and 0.5.
What arguments are passed to a generator?
Raku passes the value of zero or more prior terms in the sequence as the arguments to the generator.
How many? Well, a generator is an ordinary Raku lambda/function. Raku uses the implicit or explicit declaration of parameters to determine how many arguments to pass.
For example, in:
{42} ... * # 42 42 42 ...
the lambda doesn't declare what parameters it has. For such functions Raku presumes a signature including $_?, and thus passes the prior term, if any. (The above lambda ignores it.)
Which arguments do you need/want your generator to be passed?
One could argue that, for the sequence you're aiming to generate, you don't need/want to pass any of the prior terms. Because, arguably, none of them really matter.
From this perspective all that matters is that the Nth term computes 1/N. That is, its value is independent of the values of prior terms and just dependent on counting the number of calls.
State solutions such as {1/++$}
One way to compute this is something like:
{ state $N; $N++; 1/$N } ... *
The lambda ignores the previous term. The net result is just the desired 1 1/2 1/3 ....
(Except that you'll have to fiddle with the stringification because by default it'll use gist which will turn the 1/3 into 0.333333 or similar.)
Or, more succinctly/idiomatically:
{ 1 / ++$ } ... *
(An anonymous $ in a statement/expression is a simultaneous declaration and use of an anonymous state scalar variable.)
Solutions using the prior term
As #user0721090601++ notes in a comment below, one can write a generator that makes use of the prior value:
1/1, 1/2, 1/3, {1/(.denominator+1)} ... *
For a generator that doesn't explicitly specify its parameters, Raku passes the value of the prior term in the sequence as the argument, binding it to the "it" argument $_.
And given that there's no explicit invocant for .denominator, Raku presumes you mean to call the method on $_.
As #jjmerelo++ notes, an idiomatic way to express many lambdas is to use the explicit pronoun "whatever" instead of "it" (implicit or explicit) to form a WhateverCode lambda:
1/1, 1/2, 1/3, 1/(*.denominator+1) ... *
You drop the braces for this form, which is one of its advantages. (You can also use multiple "whatevers" in a single expression rather than just one "it", another part of this construct's charm.)
This construct typically takes some getting used to; perhaps the biggest hurdle is that a * must be combined with a "WhateverCodeable" operator/function for it to form a WhateverCode lambda.
TIMTOWTDI
routine map
(1..*).map: 1/*
List repetition operator xx
1/++$ xx *
The cross metaoperator, X or the zip metaoperator Z
1 X/ 1..*
1 xx * Z/ 1..*
(Control flow) control flow gather take
gather for 1..* { take 1/$_ }
(Seq) method from-loop
Seq.from-loop: { 1/++$ }
(Operators) infix ...
1, 1/(1+1/*) ... *
{1/++$} ... *

Languages that support boolean syntactic sugar

There's a certain over-verbosity that I have to engage in when writing certain Boolean expressions, at least with all the languages I've used, and I was wondering if there were any languages that let you write more concisely?
The way it goes is like this:
I want to find out if I have a Thing that can be either A, B, C, or D.
And I'd like to see if Thing is an A or a B.
The logical way for me to express this is
//1: true if Thing is an A or a B
Thing == (A || B)
Yet all the languages I know expect it to be written as
//2: true if Thing is an A or a B
Thing == A || Thing == B
Are there any languages that support 1? It doesn't seem problematic to me, unless Thing is a Boolean.
Yes. Icon does.
As a simple example, here is how to get the sum of all numbers less than 1000 that are divisble by three or five (the first problem of Project Euler).
procedure main ()
local result
local n
result := 0
every n := 1 to 999 do
if n % (3 | 5) == 0 then
result +:= n
write (result)
end
Note the n % (3 | 5) == 0 expression. I'm a bit fuzzy on the precise semantics, but in Icon, the concept of booleans is not like other languages. Every expression is a generator and it may pass (generating a value) or fail. When used in an if expression, a generator will continue to iterate until it passes or exhausts itself. In this case, n % (3 | 5) == 0 is a generator which uses another generator (3 | 5) to test if n is divisible by 3 or 5. (To be entirely technical, this isn't even syntactic sugar.)
Likewise, in Python (which was influenced by Icon) you can use the in statement to test for equality on multiple elements. It's a little weaker than Icon though (as in, you could not translate the modulo comparison above directly). In your case, you would write Thing in (A, B), which translates exactly to what you want.
There are other ways to express that condition without trying to add any magic to the conditional operators.
In Ruby, for example:
$> thing = "A"
=> "A"
$> ["A","B"].include? thing
=> true
I know you are looking for answers that have the functionality built into the language, but here are two other means that I find work better as they solve more problems and have been in use for many decades.
Have you considered using a preprocessor?
Also languages like Lisp have macros which is part of the language.

How does multiple assignment work?

From Section 4.1 of Programming in Lua.
In a multiple assignment, Lua first evaluates all values and only then
executes the assignments. Therefore, we can use a multiple assignment
to swap two values, as in
x, y = y, x -- swap x' fory'
How does the assignment work actually?
How multiple assignment gets implemented depends on what implementation of Lua you are using. The implementation is free to do things anyway it likes as long as it preserves the semantics. That is, no matter how things get implemented, you should get the same result as if you had saved all the values in the RHS before assigning them to the LHS, as the Lua book explains.
If you are still curious about the actual implementation, one thing you can do is see what is the bytecode that gets produced for a certain program. For example, taking the following program
local x,y = 10, 11
x,y = y,x
and passing it to the bytecode compiler (luac -l) for Lua 5.2 gives
main <lop.lua:0,0> (6 instructions at 0x9b36b50)
0+ params, 3 slots, 1 upvalue, 2 locals, 2 constants, 0 functions
1 [1] LOADK 0 -1 ; 10
2 [1] LOADK 1 -2 ; 11
3 [2] MOVE 2 1
4 [2] MOVE 1 0
5 [2] MOVE 0 2
6 [2] RETURN 0 1
The MOVE opcode assigns the value in the right register to the left register (see lopcodes.h in the Lua source for more details). Apparently, what is going on is that registers 0 and 1 are being used for x and y and slot 2 is being used as a temporary extra slot. x and y get initialized with constants in the first two opcodes and in the next three 3 opcodes a swap is performed using the "temporary" second slot, kind of like you would do by hand:
tmp = y -- MOVE 2 1
y = x -- MOVE 1 0
x = tmp -- MOVE 0 2
Given how Lua used a different approach when doing a swapping assignment and a static initialization, I wouldn't be surprised if you got different results for different kinds of multiple assignments (setting table fields is probably going to look very different, specially since then the order should matter due to metamethods...). We would need to find the part in the source where the bytecode gets emitted to be 100% sure though. And as I mentioned before, all of this might vary between Lua versions and implementations, specially if you look at LuaJIT vs PUC Lua.

Is this considered memoisation?

In optimising some code recently, we ended up performing what I think is a "type" of memoisation but I'm not sure we should be calling it that. The pseudo-code below is not the actual algorithm (since we have little need for factorials in our application, and posting said code is a firing offence) but it should be adequate for explaining my question. This was the original:
def factorial (n):
if n == 1 return 1
return n * factorial (n-1)
Simple enough, but we added fixed points so that large numbers of calculations could be avoided for larger numbers, something like:
def factorial (n):
if n == 1 return 1
if n == 10 return 3628800
if n == 20 return 2432902008176640000
if n == 30 return 265252859812191058636308480000000
if n == 40 return 815915283247897734345611269596115894272000000000
# And so on.
return n * factorial (n-1)
This, of course, meant that 12! was calculated as 12 * 11 * 3628800 rather than the less efficient 12 * 11 * 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.
But I'm wondering whether we should be calling this memoisation since that seems to be defined as remembering past results of calculations and using them. This is more about hard-coding calculations (not remembering) and using that information.
Is there a proper name for this process or can we claim that memoisation extends back not just to calculations done at run-time but also those done at compile-time and even back to those done in my head before I even start writing the code?
I'd call it pre-calculation rather than memoization. You're not really remembering any of the calculations you've done in the process of calculating a final answer for a given input, rather you're pre-calculating some fixed number of answers for specific inputs. Memoization as I understand it is really more akin to "caching" a set of results as you calculate them for later reuse. If you were to store each value calculated so that you didn't need to recalculate it again later, that would be memoization. Your solution differs in that you never store any "calculated" results from your program, only the fixed points that have been pre-calculated. With memoization if you reran the function with an input different than one of the pre-calculated ones it would not have to recalculate the result, it would simply reuse it.
Whether or not you are hard coding the results in, this is still memoization because you have already calculated results that you are expecting to calculate again. Now this may come in the form of run-time, or compile time.. but either way, it's memoization.
Memoization is done at run-time. You are optimizing at compile time. So, it is not.
See for example ... Wikipedia
Or ...
Memoization
The term memoization was coined by Donald Michie (1968) to refer to the process by which a function is made to automatically remember the results of previous computations. The idea has become more popular in recent years with the rise of functional languages; Field and Harrison (1988) devote a whole chapter to it. The basic idea is just to keep a table of previously computed input/result pairs.
Peter Norvig
University of California
(the bold is mine)
Link
def memoisation(f):
dct = {}
def myfunction(x):
if x not in dct:
dct[x] = f(x)
return dct[x]
return myfunction
#memoisation
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
def nb_appels(n):
if n==0 or n==1:
return 0
else:
return 1 + nb_appels(n-1) + 1 + nb_appels(n-2)
print(fibonacci(13))
print ('nbappel',nb_appels(13))

get output as a vector in R during a loop

How can I get the output as a vector in R?
For example, if I want to have
for (i in 1:1000) {if i mod 123345 = 0, a = list(i)}
a
but I would want to find all i that divide evenly into 123345 (i.e., factors), and not just the largest one.
There may be a more concise way to do this, but I would do it this way:
i <- 1:1000
j <- i[12345 %% i == 0 ]
The resulting vector j contains a vector of the values in i which are factors of 12345. In R the modulo operator is %% and it's a bit of a bitch to find when searching on your own. It's buried in the help document for arithmetic operators and you can find it by searching for + which must be in quotes like: ?"+" and then you have to read down a bit.
You better add a VBA tag if you want to find a VBA answer. But I suspect it will involve the VBA modulo operator ;)
JD Long's method is really the first that came to mind, but another:
Filter(function(x) !(12345 %% x), 1:1000)
I think it's kind of fun to avoid any need for an explicit assignment. (Kind of too bad to create a new function each time.) (In this case, "!" converts a non-zero value to FALSE and zero to TRUE. "Filter" picks out each element evaluating to TRUE.)
Also avoiding the need for a separate allocation and not creating a new function:
which(!(12345 %% 1:1000))
Timing:
> y <- 1:1000
> system.time(replicate(1e5, y[12345 %% y == 0 ]))
user system elapsed
8.486 0.058 8.589
> system.time(replicate(1e5, Filter(function(x) !(12345 %% x), y)))
Timing stopped at: 90.691 0.798 96.118 # I got impatient and killed it
# Even pulling the definition of the predicate outside,
# it's still too slow for me want to wait for it to finish.
# I'm surprised Filter is so slow.
> system.time(replicate(1e5, which(!12345 %% y)))
user system elapsed
11.618 0.095 11.792
So, looks like JD Long's method is the winner.
You wrote:
for (i in 1:1000) {if i mod 123345 = 0, a = list(i)} a
JD Long's code is much better, but if you wanted this loopy strategy to work try instead:
a <- vector(mode="list"); for (i in 1:1000) {if (123345 %% i == 0){ a <-c(a,i) } }
as.vector(unlist(a))