Arimaafan
Arimaafan

Reputation: 167

Treat a number as an array

As far as I know, it is impossible to perform array operations on numbers in J; e.g.

NB. In J, this won't work:
m =: 234
    +/ m
9 
    */ m
24

Since I can't do it directly, is there a way to split a number into a list and back again, like this?:

    splitFunction 234
2 3 4
    +/ (splitFunction 234)
9
    |. (splitFunction 234)
4 3 2
    concatenateFunction (4 3 2)
432

If it is not possible, is there a way to turn a number into a string, and back again? (since J treats strings as character arrays) e.g.

     |. (toString 234)
432

Upvotes: 0

Views: 220

Answers (1)

bob
bob

Reputation: 4302

Well, there is a little bit to unpack here in what your expectations would be. Let's start with

   m=:234  NB. m is the integer 234

   +/ m    NB. +/ sums across the items - only item is 234
234
   */ m    NB. */ product across the items - only item is 234
234

so there seems to be confusion between the digits of the integer 234, which would be 2 3 4 and the fact that 234 is an atom that has only one item which has a value of 234.

Moving on from that, you can deconstruct your integer using 10 & #. ^: _1 which consists of the inverse (^:_1) of Base (#.) with a left argument of 10 which allows the break up to be done in base 10. J's way of inverting a primitive is to use the Power conjunction (^:) raised to the negative 1 (_1)

   splitFunction =: 10 & #.^:_1
   concatenateFunction =: 10 & #.
   splitFunction 234
2 3 4
   +/ splitFunction 234
9
   */ splitFunction 234
24
   |. splitFunction 234
4 3 2
   concatenateFunction 2 3 4
234
       concatenateFunction splitFunction 234
    234

I think that this will do what you want, but you may want to spend a bit more time thinking about what you would have expected +/ 234 to do and whether this would be useful behaviour.

Upvotes: 4

Related Questions