What is the primary usage target? A common use of SWAP is in sorting of course, which we don't need it for in REBOL.
If you provide a swap function, I think people will expect it to work on scalar values. e.g.
swap: func [a [word!] b [word!] /local tmp][
set/any 'tmp get/any a
set/any a get/any b
set/any b get/any 'tmp
]
a: 10 b: 20
swap 'a 'b
I wouldn't guess that SWAP would take two series arguments and swap the values at their current offsets, but strong idioms for that case might feel natural eventually.
Here's how I did an internal (swap within a series) series swap function (the main thing in examples here is *not* the implementation, but the interface; how do we want it to look at feel when we use it):
swap-values: func [
"Swap the values at the specified positions in a series."
series [series!]
index-1 [number! logic! pair!]
index-2 [number! logic! pair!]
/local tmp
][
tmp: pick series index-1
poke series index-1 pick series index-2
poke series index-2 tmp
series
]
b: [1 2 3 4 5 6 7 8 9 0]
swap-values b 3 7
You could also do something like this:
swap-values-between: func [
series-1 index-1
series-2 index-2
/local tmp
][
tmp: pick series-2 index-2
poke series-2 index-2 pick series-1 index-1
poke series-1 index-1 tmp
reduce [series-1 series-2]
]
c: [1 2 3]
d: [4 5 6]
swap-values-between c 2 d 3 ; what about path notation?
Or this, which gives you the default behavior that Carl describes, but allows you to override it, and not have to make sure your series are at the proper offsets; but it separates the indexes from their associated series argument. There is also the question of what to return.
swap-values-between: func [
series-1 series-2
/at index-1 index-2
/local tmp
][
set [index-1 index-2] reduce [any [index-1 1] any [index-2 1]]
tmp: pick series-2 index-2
poke series-2 index-2 pick series-1 index-1
poke series-1 index-1 tmp
reduce [series-1 series-2]
]
c: [1 2 3]
d: [4 5 6]
swap-values-between c d
swap-values-between/at c d 2 3
What about the need to swap things in and out of a series?
exchange: func [
"Change a value in the series; return the original value."
series [series!]
index [number! logic! pair!]
value
/local val
][
val: pick series index
poke series index value
val
]
exchange-based-swap: func [series index-1 index-2] [
series/:index-2: exchange series index-1 series/:index-2
series
]
Given a SWAP function, what would the code look like to swap every two elements in a series? Every N elements?
Again, what is the primar |