質問

私はここで素敵な構文を持つ関数合成を実装しようとしてきましたが、私が持っているものです。

from functools import partial

class _compfunc(partial):
    def __lshift__(self, y):
        f = lambda *args, **kwargs: self.func(y(*args, **kwargs)) 
        return _compfunc(f)

    def __rshift__(self, y):
        f = lambda *args, **kwargs: y(self.func(*args, **kwargs)) 
        return _compfunc(f)

def composable(f):
    return _compfunc(f)

@composable    
def f1(x):
    return x * 2

@composable
def f2(x):
    return  x + 3

@composable
def f3(x):
    return (-1) * x

print f1(2) #4
print f2(2) #5
print (f1 << f2 << f1)(2) #14
print (f3 >> f2)(2) #1
print (f2 >> f3)(2) #-5

これは整数で正常に動作しますが、リスト/タプルに失敗します:

@composable
def f4(a):
    a.append(0)

print f4([1, 2]) #None

どこに間違いがありますか?

役に立ちましたか?

解決

appendはありませんインプレース加え、イグナシオバスケス - エイブラムスは(も、暗黙の)言ったように - あなたは自分の関数にreturnを追加することによって、それは引数を変更する副作用を有することが解決できつつ、それはあまりにも、渡された。

@composable
def f4(a):
    a.append(0)
    return a

また、新しいオブジェクトを作成し、返し以下、より簡潔なコードを使用するのがベストだろう

@composable
def f4(a):
  return a + [0]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top