The way Clojure code solves things are very elegant, but unusual for people without a solid background in fully functional programming languages (like me).

I’ve tried to solve simple problems from Project Euler using Clojure, but failed due the lack of that background.

One problem I was trying to solve was to sum the numbers until a limit. Let’s say I want the sum until 5, so, the math would be 1 + 2 + 3 + 4 + 5 = 15.

In JavaScript I would do something like:

function sumUntilLimit(limit) {
let counter = 0,
result = 0;
while(counter <= limit) {
result += counter;
counter++;
}
return result;
}
sumUntilLimit(5); // 15

How would you do accomplish the right result using Clojure?

Not sure how to do formatting on here so I wouldn’t have that as one line. But basically apply is going to take a given function (in this case, +) and apply it as the operand for all the items in a given collection. So (apply + [1 2 3]) will give you (+ 1 2 3). So in this case we take the range from 0 to (inc limit) because we want to add 1 to the limit given because range is non inclusive. (range 6) gives us the sequence: (0 1 2 3 4 5) I hope I’m explaining all that correctly. Seems to work in my repl at least.

I like that suggestion. That also allows you to use this for multiplication too as it takes the 0 out of the equation. You still need to increment your “limit” so it would have to be (apply + (range 1 (inc limit)). My first suggestion might be more elegant now but still isn’t as generic.