+ 6

Coding challenge #10 - Add two numbers (Functional Programming #1) (Min Chars #3)

Create a function "add" which takes one integer argument "n" and RETURNS A FUNCTION that adds n to any other number. Examples addOne = add(1) print(addOne(3)) #4 addFour = add(4) print(addFour(8)) #12 Maximum number of characters to be used in Python is 25. Good luck.

17th Jul 2017, 10:07 AM
Pixie
Pixie - avatar
9 Respostas
18th Jul 2017, 12:31 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 8
@Baptiste. I'm gonna make the next challenge REALLY difficult since you always solve them very fast!! 😉😅
17th Jul 2017, 10:56 AM
Pixie
Pixie - avatar
+ 8
@JG add() returns a function. When I say addFour=add(4), addFour(n) will have the value 4+n , since add function returns another function x+n (where x=4 in this case) When addFour(8) is called, it will return the value of 8+4=12. This concept is functional programming
17th Jul 2017, 1:06 PM
Pixie
Pixie - avatar
+ 8
In Baptiste's code, he hasnt explicitly stated another function to call. Instead, he gave it as a secondary argument. add(4)(8) will first return lambda n:4+n and then compute to 4+8=12 since the argument 8 is given.
17th Jul 2017, 1:08 PM
Pixie
Pixie - avatar
+ 5
I'm a bit confused. The func name is add, right? Then how do you use the name "addFour" as a func? Without having multiple functions?
17th Jul 2017, 12:41 PM
J.G.
J.G. - avatar
17th Jul 2017, 10:57 AM
Dennis
Dennis - avatar
+ 2
@Pixie, that would make me happy ! :D
17th Jul 2017, 10:59 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
I edited my answer to add C++ as nobody did (when I am posting this text) Thanks to your challenge, I learned basics of lambda expressions in C++ ^^
18th Jul 2017, 12:33 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
A week late, but thought it would be fun. Takes user input and checks for valid numerical input. Edit: Also totally didnt see the maximum chars part for Python lol, this is definitely more than 25 chars xD https://code.sololearn.com/ch7cR94kRAXm/?ref=app
31st Jul 2017, 4:33 PM
Vari93
Vari93 - avatar