Jump to content

Function definition: Difference between revisions

→‎{{header|Python}}: Consistency & simplification mods.
(→‎{{header|Perl 6}}: show lambdas too)
(→‎{{header|Python}}: Consistency & simplification mods.)
Line 857:
 
=={{header|Python}}==
Function definition:
Named function:
<lang python>def multiply(a, b):
return a * b</lang>
 
UnnamedLambda function definition:
<lang python>multiply = lambda a, b: a * b</lang>
 
A callable class, whichdefinition may be useful to allow both simpleallows functions and complex classes to use the same interface:
<lang python>class MultiplierMultiply:
def __init__(self):
callcount = 0
def __init__(self, a=1): pass
self.multiplicand = a
def __call__(self, a, b):
Multiplier.callcountreturn +=a 1* b
return self.multiplicand * a
m4 = Multiplier(4)
m2 = Multiplier(2)
print m4(2), m4(4), m4(12), m2(2), m2(3)
### >>> 4 8 48 4 6</lang>
 
multiply = Multiply()
(This trite example implements a simplistic "curried" multiplication class ... but also keeps track of the total number of times any instance has been called as a function. I can conceive of no useful application for it).
print multiply(2, 4) # prints 8</lang>
 
(No extra functionality is shown in ''this'' class definition).
 
=={{header|Q}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.