Currying: Difference between revisions

→‎{{header|Python}}: Defining general `curry `and `uncurry` functions in terms of lambdas
(Added Fōrmulæ)
(→‎{{header|Python}}: Defining general `curry `and `uncurry` functions in terms of lambdas)
Line 1,299:
 
=={{header|Python}}==
===Nested defs and functools.partial===
Since Python has had local functions with closures since around 1.0, it's always been possible to create curried functions manually:
<lang python> def addN(n):
Line 1,337 ⟶ 1,338:
>>> print(*double(range(5)))
0 2 4 6 8</lang>
 
===Automatic curry and uncurry functions using lambdas===
 
As an alternative to nesting defs, we can also define curried functions, perhaps more directly, in terms of lambdas.
We can also define a general '''curry''' function, and a corresponding '''uncurry''' function, for automatic derivation of curried and uncurried functions at run-time, without needing to import ''functools.partial'':
 
<lang python># AUTOMATIC CURRYING AND UNCURRYING OF EXISTING FUNCTIONS
 
 
# curry :: ((a, b) -> c) -> a -> b -> c
def curry(f):
return lambda a: lambda b: f(a, b)
 
 
# uncurry :: (a -> b -> c) -> ((a, b) -> c)
def uncurry(f):
return lambda x, y: f(x)(y)
 
 
# EXAMPLES --------------------------------------
 
# A plain uncurried function with 2 arguments,
 
# justifyLeft :: Int -> Char -> String -> String
def justifyLeft(n, s):
return (s + (n * ' '))[:n]
 
 
# and a similar, but manually curried, function.
 
# justifyRight :: Int -> String -> String
def justifyRight(n):
return lambda s: (
((n * ' ') + s)[-n:]
)
 
 
# CURRYING and UNCURRYING at run-time:
 
def main():
for s in [
'Manually curried using a lambda:',
'\n'.join(map(
justifyRight(5),
['1', '9', '10', '99', '100', '1000']
)),
 
'\nAutomatically uncurried:',
uncurry(justifyRight)(5, '10000'),
 
'\nAutomatically curried',
'\n'.join(map(
curry(justifyLeft)(10),
['1', '9', '10', '99', '100', '1000']
))
]:
print (s)
 
 
main()</lang>
{{Out}}
<pre>Manually curried using a lambda:
1
9
10
99
100
1000
 
Automatically uncurried:
10000
 
Automatically curried
1
9
10
99
100
1000 </pre>
 
=={{header|Racket}}==
9,659

edits