我试图编写一些类别理论。一个要求是关联性,所以“(ab)c = a(bc)”试图使用中缀模块进行编码,我发现我的右侧版本(“a(bc)”)没有正确运行。任何人都可以建议我做错了吗?
import infix #from https://pypi.python.org/pypi/infix/ #Thanks for the module!
from infix import or_infix
# Uses the "or" sign | around infix functions, eg "then(a,b)" becomes "a |then| b"
# Function "then(a,b)" also works and I use it first in the test below
@or_infix
def then(f,g):
'''returns a function that = g(f())'''
#assertion tests make sure arguments are functions, ie that they can be called.
assert callable(f)
assert callable(g)
def h(x):
return g(f(x))
return h
def m5(x):
print("m5 is subtracting 5")
return x-5
def p5(x):
print("p5 is adding 5")
return x+5
def double(x):
print ("double is multiplying by 2")
return 2*x
x = 0
print ("Setting the arg x to 0")
print("Using function language:")
print( then(m5,then(p5, double))(x) ) #This works and gives 0
print()
print("|then| with abbreviations:")
pd = p5 |then| double
print((m5 |then| pd)(x)) #This works and gives 0
print()
print("Straight-through with |then|")
print((m5 |then| p5 |then| double)(x)) #This works and gives 0
print()
print("Using |then| language with parentheses:")
print( (m5 |then| (p5 |then| double ))(x) ) #The problem code
#This last does not work. p5 runs twice, m5 not at all. Why, though?