Map signature mismatch with Whatever? x vs X vs xx - raku

The last line here results in a incorrect signature to the map call:
my #array=[0,1,2];
say "String Repetition";
say #array.map({($_ x 2)});
say #array.map: * x 2;
say "\nCross product ";
say #array.map({($_ X 2)});
say #array.map: * X 2;
say "\nList Repetition";
say #array.map({$_ xx 2});
say #array.map: * xx 2;
The output being:
String Repetition
(00 11 22)
(00 11 22)
Cross product
(((0 2)) ((1 2)) ((2 2)))
(((0 2)) ((1 2)) ((2 2)))
List Repetition
((0 0) (1 1) (2 2))
Cannot resolve caller map(Array:D: Seq:D); none of these signatures match:
($: Hash \h, *%_)
(\SELF: █; :$label, :$item, *%_)
The x operator returns a Str, the X returns a List of Lists and the xx return a List.
Is this changed somehow using the Whatever. Why is this error happening? Thanks in advance

Let me see if I can get this through clearly. If I don't, please ask.
Short answer: xx has a special meaning together with Whatever, so it's not creating a WhateverCode as in the rest of the examples.
Let's see if I can get this straight with the long answer.
First, definitions. * is called Whatever. It's generally used in situations in which it's curried
I'm not too happy with this name, which points at functional-language-currying, but does not seem to be used in that sense, but in the sense of stewing or baking. Anyway.
Currying it turns it into WhateverCode. So an * by itself is Whatever, * with some stuff is WhateverCode, creating a block out of thin air.
However, that does not happen automatically, because some times we need Whatever just be Whatever. You have a few exceptions listed on Whatever documentation. One of them is using xx, because xx together with Whatever should create infinite lists.
But that's not what I'm doing, you can say. * is in front of the number to multiply. Well, yes. But this code in Actions.nqp (which generates code from the source) refers to infix xx. So it does not really matter.
So, back to the short answer: you can't always use * together with other elements to create code. Some operators, such as that one, .. or ... will have special meaning in the proximity of *, so you'll need to use something else, like placeholder arguments.

The xx operator is “thunky”.
say( rand xx 2 );
# (0.7080396712923503 0.3938678220039854)
Notice that rand got executed twice. x and X don't do that.
say( rand x 2 );
0.133525574759261740.13352557475926174
say( rand X 1,2 );
((0.2969453468495996 1) (0.2969453468495996 2))
That is xx sees each side as something sort of like a lambda on their own.
(A “thunk”)
say (* + 1 xx 2);
# ({ ... } { ... })
say (* + 1 xx 2)».(5);
# (6 6)
So you get a sequence of * repeated twice.
say (* xx 2).map: {.^name}
# (Whatever Whatever)
(The term *, is an instance of Whatever)
This also means that you can't create a WhateverCode closure with && / and, || / or, ^^ / xor, or //.
say (* && 1);
# 1
Note that * also does something different on the right side of xx.
It creates an infinite sequence.
say ( 2 xx * ).head(20);
# (2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2)
If xx wasn't “thunky”, then this would also have created a WhateverCode lambda.

Related

simplifying composite function (diff) in maxima (chain rule for differentiation)

How can the following formula be simplified in Maxima:
diff(h((x-1)^2),x,1)
Mathematically it should be : 2*(x-1)*h'((x-1)^2)
But maxima gives : d/dx h((x-1)^2)
Maxima doesn't apply the chain rule by default, but there is an add-on package named pdiff (which is bundled with the Maxima installation) which can handle it.
pdiff means "positional derivative" and it uses a different, more precise, notation to indicate derivatives. I'll try it on the expression you gave.
(%i1) load ("pdiff") $
(%i2) diff (h((x - 1)^2), x);
2
(%o2) 2 h ((x - 1) ) (x - 1)
(1)
The subscript (1) indicates a first derivative with respect to the argument of h. You can convert the positional derivative to the notation which Maxima usually uses.
(%i3) convert_to_diff (%);
!
d !
(%o3) 2 (x - 1) (----- (h(g485))! )
dg485 ! 2
!g485 = (x - 1)
The made-up variable name g485 is just a place-holder; the name of the variable could be anything (and if you run this again, chances are you'll get a different variable name).
At this point you can substitute for h or x to get some specific values. Note that ev(something, nouns) means to call any quoted (evaluation postponed) functions in something; in this case, the quoted function is diff.
(%i4) ev (%, h(u) := sin(u));
!
d !
(%o4) 2 (x - 1) (----- (sin(g485))! )
dg485 ! 2
!g485 = (x - 1)
(%i5) ev (%, nouns);
2
(%o5) 2 cos((x - 1) ) (x - 1)

Exponential moving average in J

I currently am going through some examples of J, and am trying to do an exponential moving average.
For the simple moving average I have done as follows:
sma =: +/%[
With the following given:
5 sma 1 2 3 4 5
1.2 1.4 1.6 1.8 2
After some more digging I found an example of the exponential moving average in q.
.q.ema:{first[y]("f"$1-x)\x*y}
I have tried porting this to J with the following code:
ema =: ({. y (1 - x)/x*y)
However this results in the following error:
domain error
| ema=:({.y(1-x) /x*y)
This is with x = 20, and y an array of 20 random numbers.
A couple of things that I notice that might help you out.
1) When you declare a verb explicitly you need to use the : Explicit conjunction and in this case since you have a dyadic verb the correct form would be 4 : 'x contents of verb y' Your first definition of sma =: +/%[ is tacit, since no x or y variables are shown.
ema =: 4 : '({. y (1 - x)/x*y)'
2) I don't know q, but in J it looks as if you are trying to Insert / a noun 1 - x into a list of integers x * y. I am guessing that you really want to Divides %. You can use a gerunds as arguments to Insert but they are special nouns representing verbs and 1 - x does not represent a verb.
ema =: 4 : '({. y (1 - x)%x*y)'
3) The next issue is that you would have created a list of numbers with (1 - x) % x * y, but at that point y is a number adjacent to a list of numbers with no verb between which will be an error. Perhaps you meant to use y * (1 - x)%x*y ?
At this point I am not sure what you want exponential moving average to do and hope the clues I have provided will give you the boost that you need.

Questions on the prime number calculating code in Raku

I've come across this code at RosettaCode
constant #primes = 2, 3, { first * %% none(#_), (#_[* - 1], * + 2 ... Inf) } ... Inf;
say #primes[^10];
Inside the explicit generator block:
1- What or which sequence do the #_ s refer to?
2- What does the first * refer to?
3- What do the * in #_[* - 1] and the next * refer to?
4- How does the sequence (#_[* - 1], * + 2 ... Inf) serve the purpose of finding prime numbers?
Thank you.
The outer sequence operator can be understood as: start the sequence with 2 and 3, then run the code in the block to work out each of the following values, and keep going until infinity.
The sequence operator will pass that block as many arguments as it asks for. For example, the Fibonacci sequence is expressed as 1, 1, * + * ... Inf, where * + * is shorthand for a lambda -> $a, $b { $a + $b }; since this wishes for two parameters, it will be given the previous two values in the sequence.
When we use #_ in a block, it's as if we write a lambda like -> *#_ { }, which is a slurpy. When used with ..., it means that we wish to be passed all the previous values in the sequence.
The sub first takes a predicate (something we evaluate that returns true or false) and a list of values to search, and returns the first value matching the predicate. (Tip for reading things like this: whenever we do a call like function-name arg1, arg2 then we are always parsing a term for the argument, meaning that we know the * cannot be a multiplication operator here.)
The predicate we give to first is * %% none(#_). This is a closure that takes one argument and checks that it is divisible by none of the previous values in the sequence - for if it were, it could not be a prime number!
What follows, #_[* - 1], * + 2 ... Inf, is the sequence of values to search through until we find the next prime. This takes the form: first value, how to get the next value, and to keep going until infinity.
The first value is the last prime that we found. Once again, * - 1 is a closure that takes an argument and subtracts 1 from it. When we pass code to an array indexer, it is invoked with the number of elements. Thus #arr[* - 1] is the Raku idiom for "the last thing in the array", #arr[* - 2] would be "the second to last thing in the array", etc.
The * + 2 calculates the next value in the sequence, and is a closure that takes an argument and adds 2 to it. While we could in fact just do a simple range #_[* - 1] .. Inf and get a correct result, it's wasteful to check all the even numbers, thus the * + 2 is there to produce a sequence of odd numbers.
So, intuitively, this all means: the next prime is the first (odd) value that none of the previous primes divide into.

Perl6-ish expression for the bits of an integer

I've been trying to exercise my Perl 6 chops by looking at some golfing problems. One of them involved extracting the bits of an integer. I haven't been able to come up with a succinct way to write such an expression.
My "best" tries so far follow, using 2000 as the number. I don't care whether the most or least significant bit comes first.
A numeric expression:
map { $_ % 2 }, (2000, * div 2 ... * == 0)
A recursive anonymous subroutine:
{ $_ ?? ($_ % 2, |&?BLOCK($_ div 2)) !! () }(2000)
Converting to a string:
2000.fmt('%b') ~~ m:g/./
Of these, the first feels cleanest to me, but it would be really nice to be able to generate the bits in a single step, rather than mapping over an intermediate list.
Is there a cleaner, shorter, and/or more idiomatic way to get the bits, using a single expression? (That is, without writing a named function.)
The easiest way would be:
2000.base(2).comb
The .base method returns a string representation, and .comb splits it into characters - similar to your third method.
An imperative solution, least to most significant bit:
my $i = 2000; say (loop (; $i; $i +>= 1) { $i +& 1 })
The same thing rewritten using hyperoperators on a sequence:
say (2000, * +> 1 ...^ !*) >>+&>> 1
An alternative that is more useful when you need to change the base to anything above 36, is to use polymod with an infinite list of that base.
Most of the time you will have to reverse the order though.
say 2000.polymod(2 xx *);
# (0 0 0 0 1 0 1 1 1 1 1)
say 2000.polymod(2 xx *).reverse;
say [R,] 2000.polymod(2 xx*);
# (1 1 1 1 1 0 1 0 0 0 0)

How would I do this in a program? Math question

I'm trying to make a generic equation which converts a value. Here are some examples.
9,873,912 -> 9,900,000
125,930 -> 126,000
2,345 -> 2,400
280 -> 300
28 -> 30
In general, x -> n
Basically, I'm making a graph and I want to make values look nicer. If it's a 6 digit number or higher, there should be at least 3 zeros. If it's a 4 digit number or less, there should be at least 2 digit numbers, except if it's a 2 digit number, 1 zero is fine.
(Ignore the commas. They are just there to help read the examples). Anyways, I want to convert a value x to this new value n. What is an equation g(x) which spits out n?
It is for an objective-c program (iPhone app).
Divide, truncate and multiply.
10**x * int(n / 10**(x-d))
What is "x"? In your examples it's about int(log10(n))-1.
What is "d"? That's the number of significant digits. 2 or 3.
Ahhh rounding is a bit awkward in programming in general. What I would suggest is dividing by the power of ten, int cast and multiplying back. Not remarkably efficient but it will work. There may be a library that can do this in Objective-C but that I do not know.
if ( x is > 99999 ) {
x = ((int)x / 1000) * 1000;
}
else if ( x > 999 ) {
x = ((int) x / 100) * 100;
}
else if ( x > 9 ) {
x = ((int) x / 10) * 10;
}
Use standard C functions like round() or roundf()... try man round at a command line, there are several different options depending on the data type. You'll probably want to scale the values first by dividing by an appropriate number and then multiplying the result by the same number, something like:
int roundedValue = round(someNumber/scalingFactor) * scalingFactor;