[Swift-devel] Join function?

Glen Hocky glen842 at uchicago.edu
Tue Apr 3 14:09:34 CDT 2012


This seemed like an interesting challenge. The following works assuming
swift knows how many elements you have. However, there are many simpler
things I would /think/ should work that do not. There seem to possibly be
some bugs (i.e. things that don't seem intentional) about declaring a
variable before an iterate statement and then writing to it on each iterate
statement. Hence the use of lists below. I will also put a second version
after which I would think should work but does not

Working:

$ swift test.swift
> Swift svn swift-r3826 cog-r2988
> RunID: 20120403-1509-3xnsrx10
> Progress:
> SwiftScript trace: this:is:a:test
> Final status:



(string j[]) join(string s[], string c, int n){
>     j[0]="";
>     iterate i {
>         if(i<n-1){
>             j[i+1]=@strcat( j[i], s[i]+c );
>         }
>         else{
>             j[i+1]=@strcat( j[i], s[i] );
>         }
>     } until(i==n-1);
> }
> string a[];
> a[0] = "this";
> a[1] = "is";
> a[2] = "a";
> a[3] = "test";
> int nelements=4;
> string j[];
> j = join( a, ":", nelements );
> trace(j[nelements]);


Not working (error, jlist has multiple writers):

> (string j) join(string s[], string c, int n){
>     string jlist[];
>     jlist[0] = "";
>     iterate i {
>         if(i<n-1){
>             jlist[i+1]=@strcat( jlist[i], s[i]+c );
>         }
>         else{
>             jlist[i+1]=@strcat( jlist[i], s[i] );
>         }
>     } until(i==n-1);
>     j = jlist[n];
> }
> string a[];
> a[0] = "this";
> a[1] = "is";
> a[2] = "a";
> a[3] = "test";
> int nelements=4;
> string j;
> j = join( a, ":", nelements );
> trace(j);




On Tue, Apr 3, 2012 at 2:02 PM, David Kelly <davidk at ci.uchicago.edu> wrote:

> Hello,
>
> Is there a way to concatenate all elements of an array into a single
> string? I would also like to define a separator between elements. I was
> thinking of something similar to Perl's join function.
>
> If I have:
>
> string a[];
> a[0] = "this";
> a[1] = "is";
> a[2] = "a";
> a[3] = "test";
>
> How can I get it into "this is a test" or "this:is:a:test"? @strcat
> returns a reference. I can tracef with %q and get "[this,is,a,test]", but
> it doesn't give me any control over the formatting as far as I know.
>
> I could call a shell script to do this, just wondering if there was
> another way.
>
> David
> _______________________________________________
> Swift-devel mailing list
> Swift-devel at ci.uchicago.edu
> https://lists.ci.uchicago.edu/cgi-bin/mailman/listinfo/swift-devel
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.mcs.anl.gov/pipermail/swift-devel/attachments/20120403/974b0dca/attachment.html>


More information about the Swift-devel mailing list