Red: any alternative to using do for adding dynamic keys to a block - rebol

Is there an alternative syntax for :
a: [
b: [
1 2
]
]
append (do "a/b") 3
== [
b: [
1 2
]
]
I don't feel this as very elegant using do (it ressembles too much eval in javascript).
I tried to-path without success.

The simplest way is to use path notation to "address" the inner block directly:
>> a: [ b: [ 1 2 ] ]
== [b: [1 2]]
>> append a/b 3
== [1 2 3]

Re comment that you want a/b in a variable:
a: [b: [1 2 3]]
var: a/b
append var 4
probe a
== [b: [1 2 3 4]]

Given your initial assignment
a: [b: [1 2]]
== [b: [1 2]]
you want to append 3 to the inner block. You can get the inner block by
do "a/b"
== [1 2]
but you can also get it by
probe a/b
== [1 2]
which lets you append like this instead:
append a/b 3
== [1 2 3]
probe a
== [b: [1 2 3]]
In an Algol-style language, this would be something like a.b = append(a.b, 3): the a/b is an assignable dereference to the inner block.
ETA:
If you want to bottle up the dereference, the alternative to your do "a/b" could be to create a function:
ab: function [][a/b]
== func [][a/b]
append ab 7
== [1 2 7]
(Alternatively, ab: does [a/b].)

Why this doesn't work though: a: [b: [1 2 3]] var: to-path "a/b" append var 4
This does (note the GET)
a: [b: [1 2 3]]
var: load "a/b"
append get var 4
probe a
== [b: [1 2 3 4]]

As path notation is just a shortcut to select you can circumvent the path by using select
in Red
>> a: [ b: [ 1 2 ] ]
== [b: [1 2]]
>> append select a 'b 3
== [1 2 3]
>> a
== [b: [1 2 3]]
in Rebol you have to do
>> append select a to-set-word 'b 3
== [1 2 3]
By the way, why do you not use a: [ b [ 1 2 ] ] or do you want to assign the inner block to the global variable b ? Then a simple do a would do it and you can use
>> do a
== [1 2]
>> append b 3
== [1 2 3]

a: [b: [ 1 2 3]]
append a/b 4
probe a
== [b: [1 2 3 4]]

Related

Using "is default" with Hash of Arrays

Here is the working example:
my %hash;
for 1..4 -> $i {
%hash{$i} = Array.new without %hash{$i};
%hash{$i}.push: $_ for ^$i;
}
say %hash; # OUTPUT: {1 => [0], 2 => [0 1], 3 => [0 1 2], 4 => [0 1 2 3]}
But why the next similar example doesn't work?
my %hash is default(Array.new);
for 1..4 -> $i {
%hash{$i}.push: $_ for ^$i;
}
say %hash; # OUTPUT: {}
This even more confuses me, because the next example works as expected:
my %hash is default(42);
for 1..4 -> $i {
%hash{$i}.=Str;
}
say %hash.raku; # OUTPUT: {"1" => "42", "2" => "42", "3" => "42", "4" => "42"}
It's not immediately clear to me why the result of the second example is an empty hash, however using is default like this is not going to work as you wish. Traits are applied at compile time; thus is default(Array.new), even if it worked correctly, would create a single Array instance at compile time, and reuse it globally. So the output I'd expect is something like:
1 => [0 0 1 0 1 2 0 1 2 3], 2 => [0 0 1 0 1 2 0 1 2 3], 3 => [0 0 1 0 1 2 0 1 2 3], 4 => [0 0 1 0 1 2 0 1 2 3]}
That it doesn't give this is probably a bug.
However, thanks to auto-vivification, the first example can be reduced to:
my %hash;
for 1..4 -> $i {
%hash{$i}.push: $_ for ^$i;
}
say %hash; # {1 => [0], 2 => [0 1], 3 => [0 1 2], 4 => [0 1 2 3]}
The array is created automatically when doing an array operation on an undefined value anyway, thus meaning there's no use for is default in this kind of situation.

numpy return indices using multiple conditions of UNKNOWN number

Consider two arrays (X and Y), X is a 2D data array (grayscale image), and Y is an array of conditions where array X needs to be filtered based on, as follows:
X = np.array([[0,0,0,0,4], [0,1,1,2,3], [1,1,2,2,0], [0,0,2,2,3], [0,0,0,0,0]])
Y = np.array([1,2,3])
X:
[[0 0 0 0 4]
[0 1 1 2 3]
[1 1 2 2 0]
[0 0 2 2 3]
[0 0 0 0 0]]
Y:
[1 2 3]
I need to select the elements/indices of array X based on the values in array Y, such that:
Z = np.argwhere((X == Y[0]) | (X == Y[1]) | (X == Y[2]))
Z:
[[1 1]
[1 2]
[1 3]
[1 4]
[2 0]
[2 1]
[2 2]
[2 3]
[3 2]
[3 3]
[3 4]]
This can be done using a loop over the items of array Y, is there a numpy function to achieve this?
It is also achievable using multiple conditions in a np.argwhere function, however, the number of conditions (length of array Y ) is unknown beforhand.
Thanks
The key is to prepare the correct mask. For that, use numpy.isin:
np.isin(X, Y)
You'll get a boolean mask as a result, of the same shape X has. Now you can get the indices using an appropriate method.

How to access array indices in REBOL multidimensional arrays

I tried using an array to specify an index of a 2-dimensional array, but the pick function won't accept an array as the second element:
print pick [[3 5] [3 1]] [2 1]
*** ERROR
** Script error: invalid argument: [2 2]
** Where: pick try do either either either -apply-
** Near: pick [[3 5] [3 1]] [2 2]
I found a workaround for this, but it's slightly more verbose:
print pick pick [[3 5] [3 1]] 2 1
[comment This prints "3".]
Is it possible to access an index of a multidimensional array without calling the pick function multiple times?
A more succinct way to PICK out an element from a multi-dimensonal array is to use the PATH! syntax.
Here's an example in the Rebol console:
>> x: [[3 5] [3 1]]
== [[3 5] [3 1]]
>> x/2/1
== 3
>> x/2/2
== 1
>> x/1/(1 + 1) ;; use parens for expressions - transforms to x/1/2
== 5
>> p: 2
== 2
>> x/1/:p ;; use ":" for variable reference - transforms to x/1/2
== 5
>> x/(p - 1)/:p ;; mix and match at any level of array - transforms to x/1/2
== 5
>> x/3 ;; NONE is returned if index does not exist
== none
>> x/2
== [3 1]
>> x/2/3 ;; again out of range
== none
Another alternative would be the FIRST, SECOND .. TENTH functions:
>> second first [[3 5] [3 1]]
== 5
You can even mix and match:
>> x: [ [[1]] [[2]] [3 [4 5]] ]
== [[[1]] [[2]] [3 [4 5]]]
>> first pick x/3 2
== 4

How do I convert set-words in a block to words

I want to convert a block from block: [ a: 1 b: 2 ] to [a 1 b 2].
Is there an easier way of than this?
map-each word block [ either set-word? word [ to-word word ] [ word ] ]
Keeping it simple:
>> block: [a: 1 b: 2]
== [a: 1 b: 2]
>> forskip block 2 [block/1: to word! block/1]
== b
>> block
== [a 1 b 2]
I had same problem so I wrote this function. Maybe there's some simpler solution I do not know of.
flat-body-of: function [
"Change all set-words to words"
object [object! map!]
][
parse body: body-of object [
any [
change [set key set-word! (key: to word! key)] key
| skip
]
]
body
]
These'd create new blocks, but are fairly concise. For known set-word/value pairs:
collect [foreach [word val] block [keep to word! word keep val]]
Otherwise, you can use 'either as in your case:
collect [foreach val block [keep either set-word? val [to word! val][val]]]
I'd suggest that your map-each is itself fairly concise also.
I like DocKimbel's answer, but for the sake of another alternative...
for i 1 length? block 2 [poke block i to word! pick block i]
Answer from Graham Chiu:
In R2 you can do this:
>> to block! form [ a: 1 b: 2 c: 3]
== [a 1 b 2 c 3]
Or using PARSE:
block: [ a: 1 b: 2 ]
parse block [some [m: set-word! (change m to-word first m) any-type!]]

Set Difference Operation between an Object Body and a Block definition in Rebol

I want to be able to modify Object dynamically by adding / removing properties or methods on the fly. For Adding no problem, for Removing I thought about using Set Difference Math Operator but it behaves weirdly as far as I can see when removing a method from the object.
For example if I have
O: make object! [
a: 1
f: func [][]
b: 1
]
I can substract [a: 1 b: 1] with no problem
>> difference third O [b: 1 a: 1]
== [f: func [][]]
But I cannot substract f: func[][]:
>> difference third O [f: func[][]]
== [a: 1 b: func [][] func []]
>>
Output is weird (I put strange maybe it doesn't sound english as I'm not english native :) )
Why and what should I do instead ?
Thanks.
Issue #1: Difference Discards Duplicates From Both Inputs
Firstly, difference shouldn't be thought of as a "subtraction" operator. It gives you one of each element that is unique in each block:
>> difference [1 1 2 2] [2 2 2 3 3 3]
== [1 3]
>> difference [2 2 2 3 3 3] [1 1 2 2]
== [3 1]
So you'd get an equivalent set by differencing with [a: 1 b: 1] and [1 a: b:]. This is why the second 1 is missing from your final output. Even differencing with the empty set will remove any duplicate items:
>> difference [a: 1 b: 1] []
== [a: 1 b:]
If you're looking to actually search and replace a known sequential pattern, then what you want is more likely replace with your replacement as the empty set:
>> replace [a: 1 b: 1] [b: 1] []
== [a: 1]
Issue #2: Function Equality Is Based On Identity
Two separate functions with the same definition will evaluate to two distinct function objects. For instance, these two functions both take no parameters and have no body, but when you use a get-word! to fetch them and compare they are not equal:
>> foo: func [] []
>> bar: func [] []
>> :foo == :bar
== false
So another factor in your odd result is that f: is being subtracted out of the set, and the two (different) empty functions are unique and thus both members of the differenced set.
R2 is a little weirder than R3 and I can't get :o/f to work. But the following is a way to get an ''artificially correct-looking version'' of the difference you are trying to achieve:
>> foo: func [] []
>> o: make object! [a: 1 f: :foo b: 2]
>> difference third o compose [f: (:foo)]
== [a: 1 b: 2]
Here you're using the same function identity that you put in the object in the block you are subtracting.
In R3, difference does not support function values in this way. It may relate to the underlying implementation being based on map! which cannot have ''function values'' as keys. Also in Rebol 3, using difference on an object is not legal. So even your first case won't work. :(
Issue #3: This isn't how to add and remove properties
In Rebol 3 you can add properties to an object dynamically with no problems.
>> obj: object [a: 1]
== make object! [
a: 1
]
>> append obj [b: 2]
== make object! [
a: 1
b: 2
]
But as far as I know of, you cannot remove them once they have been added. You can set them to none of course, but the reflection APIs will still report them as being there.
If you want to make trying to read them throw an error you can set it to an error object and then protect them from reads. A variant of this also works in R2:
>> attempt [obj/b: to-error "invalid member"]
== none
>> probe obj
== make object! [
a: 1
b: make error! [
code: 800
type: 'User
id: 'message
arg1: "invalid member"
arg2: none
arg3: none
near: none
where: none
]
]
>> obj/b
** User error: "invalid member"
R3 takes this one step further and lets you protect the member from writes, and even hide the member from having any new bindings made to it.
>> protect 'obj/b
== obj/b
>> obj/b: 100
** Script error: protected variable - cannot modify: b
>> protect/hide 'obj/b
== obj/b
>> obj
== make object! [
a: 1
]
If you need to dynamically add and remove members in R2, you might also consider a data member in your object which is a block. Blocks and objects are interchangeable for many operations, e.g:
>> data: [a: 1 b: 2]
== [a: 1 b: 2]
>> data/a
== 1
>> data/b
== 2
And you can remove things from them...
>> remove/part (find data (to-set-word 'a)) 2
== [b: 2]
It all depends on your application. The main thing object! has going over block! is the ability to serve as a context for binding words...
You cannot dynamically add or remove words from an object in Rebol 2. If you wish to simulate this behaviour you need to create and return a new object.