Recently (in my mind) the topic of Elixir. It's a modern functional language that isn't as stiff as Haskell. Elixir has many charms, but among them, the pipe processing of functions is within me. I like it quite a lot.
Such a guy
[1, [2], 3, [4, 5] |> List.flatten |> Enum.map(&(&1 * 2))
You can pass the return value to the function on the right by using the operator |>
.
I'm using Python and I wish I could create multiple functions as above.
I made it like this.
def hoge(a, b, c, d) :
return a+b+c+d
pipe([1,2],
[
pmap(lambda x: x*2),
list,
to(hoge, [3, 4]),
print
]
)
pipe / 2, to / 2, pmap / 1 are the ones I made. Each role is pipe The first argument is the initial value for pipe processing, and the second argument is the list of functions. Implementation is
from functools import reduce
def pipe(elm, fn_list) :
return reduce(lambda x, f: f(x), fn_list, elm)
to A higher-order function that transforms a self-made function into a form suitable for a pipe function. Implementation is
def to(fn, outer_args=None) :
def _to(inner_args) :
args = outer_args+inner_args if not outer_args == None else inner_args
return fn(*args)
return _to
pmap Wrapped existing map function for pipe function In addition to this, reduce and filter are also made, but for the time being
Implementation is
def pmap(fn) :
def _pmap(li) :
return map(fn, li)
return _pmap
I am satisfied because I was able to do what I wanted to do just by doing something fairly simple. However, the writing style is very different from the standard writing style, so I thought that I could only use it with my own code.
Recommended Posts