Joe Slater on Fri, 02 Feb 2024 06:34:43 +0100


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

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


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.

Thanks,
Joe Slater