Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way to swap two elements in a vector

Is there a better or more concise way to do the following?

(defn swap [v i1 i2]
  "swap two positions in a vector"
  (let [e1 (v i1)
        e2 (v i2)]
       (-> (assoc v i1 e2)
       (assoc i2 e1))))
like image 791
Nick Orton Avatar asked May 12 '11 14:05

Nick Orton


People also ask

How do you swap two values in a vector?

The std::vector::swap() function is used to swap the entire contents of one vector with another vector of same type. If std::swap() function is used for swapping two vectors A and B, it will call specialized std::swap algorithm for std::vector which in turn calls A. swap(B) and swaps the contents.

What does std :: swap do?

The function std::swap() is a built-in function in the C++ Standard Template Library (STL) which swaps the value of two variables. Parameters: The function accepts two mandatory parameters a and b which are to be swapped. The parameters can be of any data type.


1 Answers

I can't think of a particularly elegant solution, either. Here's how I'd write it though:

(defn swap [v i1 i2] 
   (asso­c v i2 (v i1) i1 (v i2)))­
like image 113
drcode Avatar answered Sep 24 '22 04:09

drcode