Search code examples
factor-lang

destructure sequence into lexical variables


I have a sequence with a known number of elements (from a pcre match) and would like to map this into lexical variables.

I can probably loop over the sequence and put every element onto the stack and then :> ( a b c d ) but is there an idiomatic way to do this ?

Oh and my sequence has more than 4 elements, so first4 doesn't cut it, although I could obviously use first4 and then first3 on a subset of the sequence.


Solution

  • If you are sure that's want you really want to do, you could use firstn from quotations.generalizations:

    SYMBOLS: a b c d e f g h ;
    
    [let
     { 1 2 3 4 5 6 7 8 }
     8 firstn :> ( a b c d e f g h )
    
     a b c d e f g h . . . . . . . .  ]
    

    But it sounds like a bad idea. It's tricky, because the lexical variables are not "real" variables, the compiler converts them into stack shuffling. That's why they don't play nice with macros and :> can't be called like a regular word.

    If you use dynamic variables it's easier:

    SYMBOLS: a b c d e f g h ;
    
     { 1 2 3 4 5 6 7 8 }
     { a b c d e f g h } [ set ] 2each
    
     { a b c d e f g h } [ get . ] each