mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Swap Two Items in a Vector as a clojure til.
This commit is contained in:
@@ -11,6 +11,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
|||||||
|
|
||||||
- [Specify the Directory of a Shell Command](clojure/specify-the-directory-of-a-shell-command.md)
|
- [Specify the Directory of a Shell Command](clojure/specify-the-directory-of-a-shell-command.md)
|
||||||
- [Splitting On Whitespace](clojure/splitting-on-whitespace.md)
|
- [Splitting On Whitespace](clojure/splitting-on-whitespace.md)
|
||||||
|
- [Swap Two Items in a Vector](clojure/swap-two-items-in-a-vector.md)
|
||||||
- [Type of Anything](clojure/type-of-anything.md)
|
- [Type of Anything](clojure/type-of-anything.md)
|
||||||
|
|
||||||
### git
|
### git
|
||||||
|
|||||||
31
clojure/swap-two-items-in-a-vector.md
Normal file
31
clojure/swap-two-items-in-a-vector.md
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
# Swap Two Items in a Vector
|
||||||
|
|
||||||
|
If you want to replace the value at an index in a vector, you can use the
|
||||||
|
`assoc` function supplied by `clojure.core` like so:
|
||||||
|
|
||||||
|
```clojure
|
||||||
|
> (assoc [5 6 7 8] 1 9)
|
||||||
|
; [5 9 7 8]
|
||||||
|
```
|
||||||
|
|
||||||
|
Likewise, if you want to replace two items in a vector, you can extend the
|
||||||
|
above like so:
|
||||||
|
|
||||||
|
```clojure
|
||||||
|
> (assoc [5 6 7 8] 1 2 2 4)
|
||||||
|
; [5 2 4 8]
|
||||||
|
```
|
||||||
|
|
||||||
|
We can take advantage of that second example to construct a function that
|
||||||
|
will swap two values:
|
||||||
|
|
||||||
|
```clojure
|
||||||
|
(defn swap
|
||||||
|
[items i j]
|
||||||
|
(assoc items i (items j) j (items i)))
|
||||||
|
```
|
||||||
|
|
||||||
|
This function will break on values of `i` and `j` that are out of the bounds
|
||||||
|
of `items`, but dealing with that is left as an exercise to the reader.
|
||||||
|
|
||||||
|
[source](http://stackoverflow.com/questions/5979538/what-is-the-idiomatic-way-to-swap-two-elements-in-a-vector)
|
||||||
Reference in New Issue
Block a user