Paste: Swap characters in string

Author: paldepind
Mode: factor
Date: Sat, 22 Dec 2012 15:49:38
Plain Text |
: swap-char ( char1 char2 char3 -- char' )
    {
        { [ [ [ = ] 2keep ] dip 4 nrot ] [ [ 2drop ] dip ] }
        { [ [ swap ] dip [ = ] 2keep 3 nrot [ swap ] 2 ndip ] [ drop swap drop ] }
        [ 2drop ]
    } cond
;

! swaps every occurence of char1 with char2 and vice versa in string
: swap ( string char1 char2 -- string' )
    [ swap-char ] 2curry map
;

Annotation: swaps

Author: noam
Mode: factor
Date: Sat, 22 Dec 2012 22:31:25
Plain Text |
! create an associative list that maps { { c1 -> c2 } { c2 -> c1 } }
: make-swap-assoc ( c1 c2 -- alist )
    2dup swap [ 2array ] 2bi@ 2array ;

: swap-string ( s c1 c2 -- s' )
    [ make-swap-assoc ?at drop ] 2curry map ;


! Alternatively, use locals and write the following word and then map it over a string. This seems a bit clearer.

:: swap-char ( c c1 c2 -- c' )
    {
        { [ c c1 = ] [ c2 ] }
        { [ c c2 = ] [ c1 ] }
        [ c ]
    } cond ;


: swap-string ( s c1 c2 -- s' )
    [ swap-char ] 2curry map ;

New Annotation

Summary:
Author:
Mode:
Body: