File tree Expand file tree Collapse file tree 2 files changed +32
-0
lines changed Expand file tree Collapse file tree 2 files changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -11,6 +11,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
11
11
12
12
- [ Specify the Directory of a Shell Command] ( clojure/specify-the-directory-of-a-shell-command.md )
13
13
- [ Splitting On Whitespace] ( clojure/splitting-on-whitespace.md )
14
+ - [ Swap Two Items in a Vector] ( clojure/swap-two-items-in-a-vector.md )
14
15
- [ Type of Anything] ( clojure/type-of-anything.md )
15
16
16
17
### git
Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments