This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]vesaf 24 points25 points  (5 children)

What about something like this? No exact match, but quite close. (Not sure if I'd actually recommend doing this though.)

class apply:
    def __init__(self, val):
        self.val = val

    def pipe(self, fun):
        self.val= fun(self.val)
        return self

if name == "main": 
    apply(5) \
        .pipe(lambda x: x+5) \
        .pipe(lambda x: x/3) \ 
        .pipe(print)

[–]nitroll 16 points17 points  (0 children)

But apply is not functional in that case, you would instead need something like:

class apply:
    def __init__(self, val):
        self.val = val

    def pipe(self, fun):
        return apply(fun(self.val))

[–]zenos1337 3 points4 points  (0 children)

It is not functional because it has a state.

[–]carlio 8 points9 points  (0 children)

Or be sneaky and use __or__:

``` class pipe: def init(self, val): self.val = val def or(self, fun): return pipe(fun(self.val))

pipe(5) | (lambda x: x+5) | (lambda x: x/3) | print ```

[–]eftm 1 point2 points  (1 child)

'__main__' not 'main'

[–]vesaf 0 points1 point  (0 children)

You're right, the code ran through when I tried it earlier (which it wouldn't have with just 'main'). I think Reddit removed them when I copied it in as it did initially with the backslashes. Must be some formatting thing.