In APL, how can I split an integer or number into a vector containing its digits? What is the most concise (shortest) way of doing this?
4 Answers
You can use the inverse of Decode
with base 10:
10⊥⍣¯1⊢
since Decode
would take in as many digits as needed and decode them, its inverse would take a number and encode it to as many digits as needed,
or, with ⎕IO←0
, you can try to find the indexes of the formatted number inside the digits vector:
⎕D⍳⍕
This is better than the uglier use of Encode
with custom length derived by shaping an array of 10 to the length of the log10 of the input:
{⍵⊤⍨10⍴⍨⌈10⍟1+⍵}
-
Just to be complete, the "old school" encode method would be something like
(10⍴10)⊤1234567890
==1 2 3 4 5 6 7 8 9 0
Commented Jul 8, 2017 at 23:40 -
that works, but what does the
⊢
do (in your first example)? I am new to APL, and as far as I know it returns its right argument (but it doesn't have one here?).– lmq_305Commented Jul 9, 2017 at 10:40 -
@ed588 it is there to complete the expression into a train, so you can assign it to a variable as a function (
10 (⊥⍣¯1) ⊢
). the⊥⍣¯1
is a function on itself, so you need to associate the 10 somehow.– UrielCommented Jul 9, 2017 at 10:41 -
so does that mean that
f←10⊥⍣¯1⊢
is (roughly) equivalent tof←{10(⊥⍣¯1)⍵}
?– lmq_305Commented Jul 9, 2017 at 11:32 -
@ed588 not just roughly; another common form is
(10∘⊥⍣¯1)
which means (roughly) "compose 10 as constant first argument of this function"– UrielCommented Jul 9, 2017 at 11:35
I did this in APL2 by first applying FORMAT and then EXECUTE EACH (though it might be limited to positive integers) :
⍎¨⍕
-
1As simple (though doubtlessly inefficient) as that is, I never would have thought of it. Yet another example of how there's always a dozen ways to do the same thing in APL. Commented Aug 20, 2017 at 18:37
Not the most concise, but the power to do this was in the earliest APL. The 1962 book shows how to work with positional number systems using only basic functions and matrix multiply:
I tried to do it obviously:
a⊤⍨10×b÷b←⍳⌈10⍟a←⍵
-
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.– Community BotCommented Nov 6, 2021 at 16:39