Here is a problem Statement :
Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
The solution is long,
(defn large [x y]
(if (> x y) x y))
(defn large-3 [x y z]
(if(> (large x y) z) (large x y) z))
(defn small [x y]
(if (< x y) x y))
(defn small-3 [x y z]
(if (< (small x y) z ) (small x y) z))
(defn second-largest [x y z]
(let [greatest (large-3 x y z)
smallest (small-3 x y z)]
(first (filter #(and (> greatest %) (< smallest %)) [x y z]))))
(defn square [a]
(* a a)
)
(defn sum-of-square [x y z]
(+ (square (large-3 x y z)) (square (second-largest x y z))))
Just wanted to know what different/succinct ways this problem can be solved in Clojure.
(See a sequence version of the problem together with a lazy solution in my second update to this answer below.)
Update:
To expand on the comments from the above, the first version’s straighforward generalisation is to this:
The second version straightforwardly generalises to the version Arthur posted in the meantime:
Also, I’ve seen exactly the same problem being solved in Scheme, possibly even on SO… It included some fun solutions, like one which calculated the some of all three squares, then subtracted the smallest square (that’s very straightforward to express with Scheme primitives). That’s ‘unefficient’ in that it calculates the one extra square, but it’s certainly very readable. Can’t seem to find the link now, unfortunately.
Update 2:
In response to Arthur Ulfeldt’s comment on the question, a lazy solution to a (hopefully fun) different version of the problem. Code first, explanation below:
The
clojure.contrib.seq-utils(orc.c.seq) lib is there for thereductionsfunction.iteratecould be used instead, but not without some added complexity (unless one would be willing to calculate the length of the seq of numbers to be processed at the start, which would be at odds with the goal of remaining as lazy as possible).Explanation with example of use:
Generally,
(moving-sum-of-smaller-squares pred n & nums)generates a lazy seq of sums of squares of thenpred-smallest numbers in increasingly long initial fragments of the original seq of numbers, where ‘pred-smallest’ means smallest with regard to the ordering induced by the predicatepred. Withpred=>, the sum ofngreatest squares is calculated.This function uses the trick I mentioned above when describing the Scheme solution which summed three squares, then subtracted the smallest one, and so is able to adjust the running sum by the correct amount without recalculating it at each step.
On the other hand, it does perform a lot of sorting; I find it’s not really worthwhile to try and optimise this part, as the seqs being sorted are always
nelements long and there’s a maximum of one sorting operation at each step (none if the sum doesn’t require adjustment).