Today we have a quirky problem that requires knowledge of higher-order functions, recursion, and advanced language features. It’s an add function that returns an adder function.
The problem is to create a function that will add numbers together when called in succession.
Example
add(1)(2) == 3
It should chain as many times as we want so
add(1)(1)(1)(1) == 4
But wait, there’s more!
If called once it should return the adder function and also be equal to the number given. So;
add(1) == 1
const adder = add(1)
adder + 1 == 2
adder(2) == 3
Code language: JavaScript (javascript)
I’m not sure how you would do it in other languages but in javascript, the solution is 3 lines long but takes a second to wrap your head around. This actually took me a while to figure out so I’m pretty bummed it was so short.
function add(a) {
const adder = b => add(a + b)
adder.valueOf = () => a
return adder
}
Code language: JavaScript (javascript)
So we create an adder function that calls the calling functions with the sum then we change how that adder function is represented using valueOf.
I won’t go into greater detail here but in short:
In summary, defining a problem in terms of itself. I.e. when you have a function that calls itself. I won’t go into it here, but it’s an advanced programming technique that makes it very easy to fill up your memory.
Basically functions that use and operate on other functions. They can receive functions as arguments and return functions as values.
This is not the official term but I like it so I’m using it. Since functions are treated like any other object in javascript you can change how they are represented. You can override either the valueOf
or the toString
methods to achieve this.
In normal everyday programming, you don’t really use this feature but it’s there because reasons.
This problem looks simple but it exercised my JavaScript knowledge. It reminded me that there is still so much I don’t know and renewed my drive to master this weird weird language.
If you have another solution perhaps in another language please feel free to share it. You can contact me on Twitter @phoexer and as always happy coding.
Today I am working on a summation problem made to look like building a tower out of cubic bricks. It’s fun to brute force sometimes.
Coming back to Rust code after a bit of a hiatus with a simple problem… The Two-sum problem. Finding numbers in an array. Yay, fun.
King Pinn: I Salute You. I’m driving halfway across the country and this song is on repeat. Rest in Peace Tonderai Makoni. You were awesome.
After a few weeks off I’m back to business. This is just an update post detailing plans for the rest of the year.
At last we finally have the great reveal, our mystery project was implementing RSA encryption in rust.