Time Warping Variable Initialization? - variables

In the following simple for loop we create an array (#a) by incrementing a typeless variable ($n):
my #a = do for 1..3 {
state $n;
$n.^name, $n++;
}
say #a;
The result is "kind of" expected:
[(Any 0) (Int 1) (Int 2)]
And I say "kind of" because I've expected as the first value of $n the "undefined" value (Any).
It is like, after the first value is produced (Any) and as we increment the $n (after the first increment of $n we have a casting to an Int) there is also some time warping event in the assignment and we get also the first value to change. So we end up having the first value as 0 (zero).
Can somebody explain the exact mechanism of this behaviour?

see Any.pm6#L519, the candidate
multi sub postfix:<++>(Mu:U $a is rw) { $a = 1; 0 }
is used.
There are some another candidates for undefined values, you can try
my Bool $x;
dd $x++; #Bool::False
my Num $y;
dd $y++; #0e0

Related

IIFE alternatives in Raku

In Ruby I can group together some lines of code like so with a begin block:
x = begin
puts "Hi!"
a = 2
b = 3
a + b
end
puts x # 5
it's immediately evaluated and its value is the last value of the block (a + b here) (Javascripters do a similar thing with IIFEs)
What are the ways to do this in Raku? Is there anything smoother than:
my $x = ({
say "Hi!";
my $a = 2;
my $b = 3;
$a + $b;
})();
say $x; # 5
Insert a do in front of the block. This tells Raku to:
Immediately do whatever follows the do on its right hand side;
Return the value to the do's left hand side:
my $x = do {
put "Hi!";
my $a = 2;
my $b = 3;
$a + $b;
}
That said, one rarely needs to use do.
Instead, there are many other IIFE forms in Raku that just work naturally without fuss. I'll mention just two because they're used extensively in Raku code:
with whatever { .foo } else { .bar }
You might think I'm being silly, but those are two IIFEs. They form lexical scopes, have parameter lists, bind from arguments, the works. Loads of Raku constructs work like that.
In the above case where I haven't written an explicit parameter list, this isn't obvious. The fact that .foo is called on whatever if whatever is defined, and .bar is called on it if it isn't, is both implicit and due to the particular IIFE calling behavior of with.
See also if, while, given, and many, many more.
What's going on becomes more obvious if you introduce an explicit parameter list with ->:
for whatever -> $a, $b { say $a + $b }
That iterates whatever, binding two consecutive elements from it to $a and $b, until whatever is empty. If it has an odd number of elements, one might write:
for whatever -> $a, $b? { say $a + $b }
And so on.
Bottom line: a huge number of occurrences of {...} in Raku are IIFEs, even if they don't look like it. But if they're immediately after an =, Raku defaults to assuming you want to assign the lambda rather than immediately executing it, so you need to insert a do in that particular case.
Welcome to Raku!
my $x = BEGIN {
say "Hi!";
my $a = 2;
my $b = 3;
$a + $b;
}
I guess the common ancestry of Raku and Ruby shows :-)
Also note that to create a constant, you can also use constant:
my constant $x = do {
say "Hi!";
my $a = 2;
my $b = 3;
$a + $b;
}
If you can have a single statement, you can leave off the braces:
my $x = BEGIN 2 + 3;
or:
my constant $x = 2 + 3;
Regarding blocks: if they are in sink context (similar to "void" context in some languages), then they will execute just like that:
{
say "Executing block";
}
No need to explicitely call it: it will be called for you :-)

Why are the "increment" and "decrement" operators not composable in Kotlin?

If I have a var i : Int = 0, then i.inc().inc() works just fine, i.e. inc() is composable with itself. Why then does (i++)++ make Kotlin report the error "Variable expected"?
The effect of computing the expression [a++] is:
Store the initial value of a to a temporary storage a0.
Assign the result of a0.inc() to a.
Return a0 as the result of the expression.
So if you tried to use i++ as a above to determine the meaning of (i++)++, it would translate to
val i1 = i++
i++ = i1.inc()
i1
Of course, i++ = i1.inc() doesn't make sense (never mind that it would also calculate i++ twice).
When you call inc(), it returns a new Int and does nothing to the property or variable that held the original value. When you use it as an operator, it is interpreted as also setting the return value on the original property or variable. This cannot conceptually extend to using it as an operator on something that is not a variable or value.

This expression has type 'a -> 'a array array but an expression was expected of type 'b array

How is it possible to correctly manipulate a matrix in Ocaml?
What am I missing here, when assigning a value to a position on the matrix?
let dynamic arraymoedas valor len =
let arrayAux = Array.make_matrix (len+1) (len+1) in
for i=0 to len+1 do
arrayAux.(i).(0)=0;
done;
for j=0 to valor+1 do
arrayAux.(0).(j)= max_int
done;
for i=1 to len+1 do
for j=1 to len+1 do
if(arraymoedas.(i-j) > j) then
arrayAux.(i).(j) = arrayAux.(i - 1).(j)
else
arrayAux.(i).(j) = min (1+arrayAux.(i).(j-arraymoedas.(i - 1))) arrayAux.(i-1).(j)
done;
done;
!arrayAux
Error:
File "Novo_func.ml", line 38, characters 8-16:
38 | arrayAux.(i)(0)=0;
^^^^^^^^
Error: This expression has type 'a -> 'a array array
but an expression was expected of type 'b array
As identified in the comments, there are three issues with the code you've written.
Primarily, you're not using Array.make_matrix properly. This function has type int -> int -> 'a -> 'a array array. You've only supplied the dimensions, but not a default value. When you do this, you get back a function that takes in the default value and returns an array of arrays.
Secondly, when modifying the values in an array, use <- instead of =. Rather than arrayAux.(0).(j) = max_int you want to use arrayAux.(0).(j) <- max_int.
Thirdly, at the end of your dynamic function, you're using the ! operator to deref arrayAux. The problem with this is that arrayAux is not a reference. This will cause a compiler error due to a type mismatch.

Why does `variable++` increment the variable but `variable + 1` does not?

Here's the problem in which I encountered this issue:
The function should compare the value at each index position and score a point if the value for that position is higher. No point if they are the same. Given a = [1, 1, 1] b = [1, 0, 0] output should be [2, 0]
fun compareArrays(a: Array<Int>, b: Array<Int>): Array<Int> {
var aRetVal:Int = 0
var bRetVal:Int = 0
for(i in 0..2){
when {
a[i] > b[i] -> aRetVal + 1 // This does not add 1 to the variable
b[i] > a[i] -> bRetVal++ // This does...
}
}
return arrayOf(aRetVal, bRetVal)
}
The IDE even says that aRetVal is unmodified and should be declared as a val
What others said is true, but in Kotlin there's more. ++ is just syntactic sugar and under the hood it will call inc() on that variable. The same applies to --, which causes dec() to be invoked (see documentation). In other words a++ is equivalent to a.inc() (for Int or other primitive types that gets optimised by the compiler and increment happens without any method call) followed by a reassignment of a to the incremented value.
As a bonus, consider the following code:
fun main() {
var i = 0
val x = when {
i < 5 -> i++
else -> -1
}
println(x) // prints 0
println(i) // prints 1
val y = when {
i < 5 -> ++i
else -> -1
}
println(y) // prints 2
println(i) // prints 2
}
The explanation for that comes from the documentation I linked above:
The compiler performs the following steps for resolution of an operator in the postfix form, e.g. a++:
Store the initial value of a to a temporary storage a0;
Assign the result of a.inc() to a;
Return a0 as a result of the expression.
...
For the prefix forms ++a and --a resolution works the same way, and the effect is:
Assign the result of a.inc() to a;
Return the new value of a as a result of the expression.
Because
variable++ is shortcut for variable = variable + 1 (i.e. with assignment)
and
variable + 1 is "shortcut" for variable + 1 (i.e. without assignment, and actually not a shortcut at all).
That is because what notation a++ does is actually a=a+1, not just a+1. As you can see, a+1 will return a value that is bigger by one than a, but not overwrite a itself.
Hope this helps. Cheers!
The equivalent to a++ is a = a + 1, you have to do a reassignment which the inc operator does as well.
This is not related to Kotlin but a thing you'll find in pretty much any other language

Objective C, difference between n++ and ++n

In Objective-C, is there any difference between n++ and ++n (eg. used in a for loop)?
++n; increments the value of n before the expression is evaluated.
n++; increments the value of n after the expression is evaluated.
So compare the results of this
int n = 41;
int o = ++n; //n = 42, o = 42
with the results of this:
int n = 41;
int o = n++; //n = 42, o = 41
In the case of loops:
for (int i = 0; i < j; i++) {/*...*/}
however it doesn't make any difference, unless you had something like this:
for (int i = 0; i < j; x = i++) {/*...*/}
or this:
for (int i = 0; i < j; x = ++i) {/*...*/}
One could say:
It doesn't matter whether to use n++ or ++n as long as no second (related) variable is modified (based on n) within the same expression.
The same rules apply to --n; and n--;, obviously.
++n increments the value before it's used (pre-increment) and n++ increments after (post-increment).
In the context of a for loop, there is no observable difference, as the increment is applied after the code in the loop has been executed.
++n and n++ differ in what the expression evaluates to. An example:
int n = 0;
NSLog(#"%d", n); // 0
NSLog(#"%d", n++); // still 0, increments afterwards
NSLog(#"%d", n); // 1
NSLog(#"%d", ++n); // 2, because it increments first
NSLog(#"%d", n); // 2
In a loop it wont make a difference. Some people say ++n is faster though
In Scott Meyers "More Effective C++" Book he makes a very rational case for preferring prefix increment to postfix increment. In a nutshell, in that language due to operator overloading facilities prefix increment is almost always faster. Objective C doesn't support overloaded operators but if you have or ever will do any C++ or Objective-C++ programming then preferring prefix increment is a good habit to get into.
Remember that most of the time ++n looks like:
n = n + 1
[do something with n]
Whereas n++ looks like (if used as intended):
register A = n; // copy n
[do something with n]
n = A + 1;
As you can see the postfix case has more instructions. In simple for loops most compilers are smart enough to avoid the copy if it's obvious that the pre-increment n isn't going to be used but that case devolves to the prefix case.
I Hope this makes sense. In summary you should use prefix unless you really want the "side-effect" behavior of evaluate then increment that you get from the postfix version.
As stated above,
--n decrements the value of n before the expression is evaluated.
n--; decrements the value of n after the expression is evaluated.
The thing here to note is when using while loops
For example:
n = 5
while(n--) #Runs the loop 5 times
while(--n) #Runs the loop 4 times
As in n-- the loop runs extra time while n = 1
But in --n 1 is first decremented to 0, and then evaluated. This causes the while loop to break.