Functional pipes in python like %>% from R's magritrr

后端 未结 14 2195
春和景丽
春和景丽 2020-11-29 16:17

In R (thanks to magritrr) you can now perform operations with a more functional piping syntax via %>%. This means that instead of coding this: <

14条回答
  •  春和景丽
    2020-11-29 16:48

    Adding my 2c. I personally use package fn for functional style programming. Your example translates into

    from fn import F, _
    from math import sqrt
    
    (F(sqrt) >> _**2 >> str)(12)
    

    F is a wrapper class with functional-style syntactic sugar for partial application and composition. _ is a Scala-style constructor for anonymous functions (similar to Python's lambda); it represents a variable, hence you can combine several _ objects in one expression to get a function with more arguments (e.g. _ + _ is equivalent to lambda a, b: a + b). F(sqrt) >> _**2 >> str results in a Callable object that can be used as many times as you want.

提交回复
热议问题