Ruud H.G. van Tol on Fri, 02 Feb 2024 12:13:59 +0100


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: How to perform concat()s without errors on empty vectors or conversions on single-element vectors??



On 2024-02-02 06:34, Joe Slater wrote:
I want to convert a vector whose members may be vectors into one long vector. This can be done using concat(), but I have two problems: 1) it fails when the vector is empty, rather than returning the empty vector; and 2) when the vector has a single element it returns that element rather than a vector.

I.e., I input:
(16:29) > v=[[1,2],[1,[2,3]],[[1,2],[3,4]],[1],[]]; for(x=1,#v,print(concat(v[x])))
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
1
  ***   at top-level: ...[1],[]];for(x=1,#v,print(concat(v[x])))
  *** ^--------------
  *** concat: domain error in concat: vector = []
  ***   Break loop: type 'break' to go back to GP prompt
What I want to get is the following, with no errors:
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1]
[]

I can do this with explicit testing, but it seems to me there should be a more natural way.


This works for your example:

? {
  my(v=[[1,2],[1,[2,3]],[[1,2],[3,4]],[1],[]]);
  [ if("t_VEC"==type(t) && #t>1, concat(t), concat([],t)) |t<-v ]
}
% [[1, 2], [1, 2, 3], [1, 2, 3, 4], [1], []]


but likely needs to go recursive if the shape is hairier, like:

? {
  my(v=[[1,2],[1,[2,3]],[[1,2],[3,4],[5,[6,7]]],[1],[]]);
  [ if("t_VEC"==type(t) && #t>1, concat(t), concat([],t)) |t<-v ]
}
% [[1, 2], [1, 2, 3], [1, 2, 3, 4, 5, [6, 7]], [1], []]


So create some flatten(v) function?

-- Ruud