Sometimes my APL familiarity gives me algorithmic ideas for problem solving that I re-implement in a language I have – Perl, for example.
So I have processed a text file to create a boolean vector indicating the used fields in a delimited file, and now I want to output the indexes of those used fields, and the names of the used fields. In APL, I would use the compress operator over the vector of field names, and over the iota of the number of fields.
In Perl, I did this:
my @UsedFieldNames = map { $UsedFields[$_] ? $FieldNames[$_] : () } 0 .. $#UsedFields;
and
say join " ", map { $UsedFields[$_] ? $) : () } 0 .. $#UsedFields;
where @UsedFields is an array containing 0 for unused and 1 for used fields.
-
I don’t really like using map with
?:()to simulate compress – is there a better way (my real program does it a third time when simulating a vertical or reduction over the file)? -
I don’t really like doing the map over the indexes to get the results – is there a better way to compute that? (I guess one optimization would be to compute the used indexes first, then
@UsedFieldNames = @FieldNames[@UsedIndexes];
Other ways: