erg/doc/JA/syntax/31_pipeline.md
2022-08-11 18:30:32 +09:00

1 KiB

パイプライン演算子

パイプライン演算子は、次のように使う。

assert f(g(x)) == (x |> g |> f)
assert f(g(x, y)) == ((x, y) |> g |> f)

つまり、Callable(object)という順序をobject |> Callableと変えられるのである。 パイプライン演算子はメソッドに対しても使える。メソッドの場合、object.method(args)object |>.method(args)と変わる。 単に|>が増えただけにも見えるが、結合強度が低めなので()の量を減らせる場合がある。

rand = -1.0..1.0 |>.sample!()
log rand # 0.2597...
1+1*2 |>.times do log("a", end: "") # aaa
# without `|>`, the following will be `evens = (1..100).iter().filter(i -> i % 2 == 0).collect(Array)`
evens = 1..100 |>.iter |>.filter i -> i % 2 == 0 |>.collect Array
# or
_evens = 1..100 \
    .iter() \
    .filter i -> i % 2 == 0 \
    .collect Array

Previous | Next