Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have a complex box,

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

Suppose I know the address of inner box [5 6] is ( 1 1 0 ), i.e. the data can be extracted like this:

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

My question is, how to write a function (verb) to amend the data given the address? e.g. the address ( 1 1 0 ) is known, I want to change the value (5 6) into a small box (<123), the output should be:

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

It may be achieved by a recursive function, but I'm wondering if the address can be applied directly, just like the way >0{>1{>1{a.

Thanks for the help!

like image 995
Ellie Y Avatar asked Mar 14 '18 22:03

Ellie Y


1 Answers

You can determine the address (1;1;0) of the item that you are looking to replace/amend 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 of {::, fetch, will return the item from the nested structure.

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

Unfortunately there is not currently an }:: equivalent to amend (}) although there is a recent request to implement the primitive }:: in the interpreter that has the functionality you desire.

While we wait for that primitive to be implemented, a search back through the J Programming forum archive revealed a post that suggested the following recursive adverb that does what you have 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 your question has been also been asked and answered on the J Forum. In the interests of completeness I've added a link to that more general solution.

   (<123) [ applyintree (1;1;0) a
┌─────┬───────────────┐
│1 2 3│┌─┬───────────┐│
│     ││4│┌─────┬───┐││
│     ││ ││┌───┐│7 8│││
│     ││ │││123││   │││
│     ││ ││└───┘│   │││
│     ││ │└─────┴───┘││
│     │└─┴───────────┘│
└─────┴───────────────┘
like image 174
Tikkanz Avatar answered Sep 20 '22 12:09

Tikkanz