Reputation:
My string of code currently is:
def makeTriangle(sign):
def triangle(n):
result = ''
for i in range(1,n+1):
result += sign * i + '\n'
return result
return
how do i actually pass the sign from MakeTriangle(sign) into triangle(n) using higher order function?
Upvotes: 0
Views: 110
Reputation: 5954
You just need to return triangle otherwise it's thrown away. Since this pattern seems to cause some confusion:
def makeTriangle(sign):
def triangle(n):
result = ''
for i in range(1,n+1):
result += sign * i + '\n'
return result
return triangle # returns a function wrapped in an enclosing scope
triangle_maker = makeTriangle("+")
# triangle_maker is a `triangle()` function, locked in a scope where `sign=+`.
triange_maker(3)
# calls the `triangle()` function
The other option for this pattern is to use functools.partial
:
from functools import partial
def triangle(sign, n):
result = ""
for i in range(1, n+1):
result += sign * i + "\n"
return result
# call without caching arg:
triangle("+",3)
# make partial function:
plus_triangle = partial(triangle, "+")
plus_triangle(3)
This saves one having to write out the container function every time, but it is of course much more limited than a full closure.
Upvotes: 1