pampy icon indicating copy to clipboard operation
pampy copied to clipboard

Proposed New Syntax

Open catethos opened this issue 5 years ago • 1 comments

I always want to write something like Haskell in Python

with Multimethod() as fib:
    fib[1] = 1
    fib[2] = 2
    fib[int] = lambda n: fib(n-1) + fib(n-2)

and this can be done by leveraging the pampy package and some simple clasees

class Matcher:
    def __init__(self):
        self.pattern = []
    
    def __setitem__(self, pat, method):
        self.pattern.append(pat)
        self.pattern.append(method)
        
    def __call__(self, *x):
        if len(x)==1:
            x = x[0]
        return match(x, *self.pattern)
class Multimethod:
    
    def __init__(self, *sig):
        pass
    
    def __enter__(self):
        return Matcher()
    
    def __exit__(self, *args):
        pass

Would it be good to have something like this inside the package?

catethos avatar Oct 14 '19 10:10 catethos

I think this is interesting, as it lets you dynamically add new patterns dynamically - something I find myself wanting.

convert = Matcher()
convert[int] = lambda x: 'integer'
convert[str] = lambda x: 'string'
# etc

It would be even better if we had proper anonymous functions.

adamlwgriffiths avatar Apr 05 '21 05:04 adamlwgriffiths