Skip to content

Commit 7bc517b

Browse files
committed
Add Swap Two Items in a Vector as a clojure til.
1 parent fdde14e commit 7bc517b

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1111

1212
- [Specify the Directory of a Shell Command](clojure/specify-the-directory-of-a-shell-command.md)
1313
- [Splitting On Whitespace](clojure/splitting-on-whitespace.md)
14+
- [Swap Two Items in a Vector](clojure/swap-two-items-in-a-vector.md)
1415
- [Type of Anything](clojure/type-of-anything.md)
1516

1617
### git

clojure/swap-two-items-in-a-vector.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Swap Two Items in a Vector
2+
3+
If you want to replace the value at an index in a vector, you can use the
4+
`assoc` function supplied by `clojure.core` like so:
5+
6+
```clojure
7+
> (assoc [5 6 7 8] 1 9)
8+
; [5 9 7 8]
9+
```
10+
11+
Likewise, if you want to replace two items in a vector, you can extend the
12+
above like so:
13+
14+
```clojure
15+
> (assoc [5 6 7 8] 1 2 2 4)
16+
; [5 2 4 8]
17+
```
18+
19+
We can take advantage of that second example to construct a function that
20+
will swap two values:
21+
22+
```clojure
23+
(defn swap
24+
[items i j]
25+
(assoc items i (items j) j (items i)))
26+
```
27+
28+
This function will break on values of `i` and `j` that are out of the bounds
29+
of `items`, but dealing with that is left as an exercise to the reader.
30+
31+
[source](http://stackoverflow.com/questions/5979538/what-is-the-idiomatic-way-to-swap-two-elements-in-a-vector)

0 commit comments

Comments
 (0)