0

I wanted to ask, if it is possible to write the below function below, If so how can I do it ?

def builder(x):
def perform_addition(y):
    return x+y

return perform_addition

result = builder(6)

print(result(8))

Attiq Rahman
  • 173
  • 1
  • 6
  • https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions – Rivo R. Nov 22 '22 at 14:17
  • 2
    @PanagiotisKanavos These aren't local functions, though you could implement them with one, it's not the same thing – DavidG Nov 22 '22 at 14:17
  • 2
    It looks like the nesting is somewhat irrelevant - it's partial function application that you're really after. You might want to read my blog post about that... https://codeblog.jonskeet.uk/2012/01/30/currying-vs-partial-function-application/ – Jon Skeet Nov 22 '22 at 14:17
  • What are you trying to do? There may be a better feature for this, or the actual problem may be solved already. For partial application you don't need a "nested" function – Panagiotis Kanavos Nov 22 '22 at 14:17
  • I'm also not sure this is valid Python, did you mean to indent the second line onwards? – DavidG Nov 22 '22 at 14:20
  • yes sorry for the format. the second function is an inner function. and the outer function is actually returning the inner function. So, what should be the return type on c# outer function ? – Attiq Rahman Nov 22 '22 at 14:21
  • 1
    For example `public static Func MyAdder(int x)=> (y)=>x+y;`. This can be used as`var adder=MyAdder(5); Console.WriteLine(adder(8));`. If you want to add all items in a list though, LINQ's `Sum` would be better, eg `var total=list.Sum();`. Or `Aggregate` for more complex operations – Panagiotis Kanavos Nov 22 '22 at 14:21
  • 1
    From C# 7.0 this is supported : https://www.geeksforgeeks.org/local-function-in-c-sharp/ – PaulF Nov 22 '22 at 14:27

0 Answers0