How to change data in a box? (J programming)

I have a complicated box,

a =: 1 2 3 ; <4 ; < 5 6; <7 8 ┌─────┬─────────────┐ │1 2 3│┌─┬─────────┐│ │ ││4│┌───┬───┐││ │ ││ ││5 67 8│││ │ ││ │└───┴───┘││ │ │└─┴─────────┘│ └─────┴─────────────┘ 

Suppose that I know that the address of the indoor unit [5 6] is (1 1 0), that is, the data can be extracted as follows:

  >0{>1{>1{a 5 6 

My question is how to write a function (verb) to change the data specified in the address? for example, the address (1 1 0) is known, I want to change the value (5 6) to a small box (<123), the output should be:

 ┌─────┬───────────────┐ │1 2 3│┌─┬───────────┐│ │ ││4│┌─────┬───┐││ │ ││ ││┌───┐│7 8│││ │ ││ │││123││ │││ │ ││ ││└───┘│ │││ │ ││ │└─────┴───┘││ │ │└─┴───────────┘│ └─────┴───────────────┘ 

This can be achieved using a recursive function, but I wonder if the address can be applied directly, just like the path> 0 {> 1 {> 1 {a.

Thanks for the help!

+5
source share
1 answer

You can determine the address ( 1;1;0 ) of the element you want to replace / fix using the monadic primitive map ( {:: :):

  a=: 1 2 3;<4;<5 6;7 8 {:: a ┌───┬─────────────────────────┐ │┌─┐│┌─────┬─────────────────┐│ ││0│││┌─┬─┐│┌───────┬───────┐││ │└─┘│││1│0│││┌─┬─┬─┐│┌─┬─┬─┐│││ │ ││└─┴─┘│││1│1│0│││1│1│1││││ │ ││ ││└─┴─┴─┘│└─┴─┴─┘│││ │ ││ │└───────┴───────┘││ │ │└─────┴─────────────────┘│ └───┴─────────────────────────┘ 

The dyadic form {:: , fetch , will return an element from a nested structure.

  (1;1;0) {:: a 5 6 

Unfortunately, there is currently no }:: equivalent to modify ( } ), although there is a recent request to implement the primitive }:: in an interpreter that has the desired functionality.

While we expect this primitive to be implemented, a search through the archive of the J-programming forum showed a message that suggested the following recursive adverb that does what you asked for:

 store=: adverb define : if. #m do. (< x (}.u)store ({.u){::y) ({.m)} y else. x end. ) (<123) (1;1;0) store a ┌─────┬───────────────┐ │1 2 3│┌─┬───────────┐│ │ ││4│┌─────┬───┐││ │ ││ ││┌───┐│7 8│││ │ ││ │││123││ │││ │ ││ ││└───┘│ │││ │ ││ │└─────┴───┘││ │ │└─┴───────────┘│ └─────┴───────────────┘ 

I see that your question was also asked and answered on the J-forum . In the interest of completeness, I added a link to a more general solution .

  (<123) [ applyintree (1;1;0) a ┌─────┬───────────────┐ │1 2 3│┌─┬───────────┐│ │ ││4│┌─────┬───┐││ │ ││ ││┌───┐│7 8│││ │ ││ │││123││ │││ │ ││ ││└───┘│ │││ │ ││ │└─────┴───┘││ │ │└─┴───────────┘│ └─────┴───────────────┘ 
+4
source

Source: https://habr.com/ru/post/1275896/


All Articles