add F#-style "pipe" operator |>
See original GitHub issueSeveral times in the past, users (including me!) have requested an F#-style pipe operator, which accepts any type T
has the left operand, and a unary function type F(T)
as the right operand.
val |> fun
would be an abbreviation for:
let (_ = val) fun(_)
Thus, you could write print("hello")
as "hello" |> print
.
If I’m not mistaken, |>
is naturally left-associative.
I’m now favorably-disposed toward this proposal, and the syntax seems viable. It looks like it can be implemented by desugaring and need not impact the backends in the initial implementation.
An open question is: is foo |> bar
considered a legal statement? Can I write this:
void hello() {
"hello" |> print;
}
I would say that we should accept this code.
Discussion on Gitter led to me proposing two additional variations of this operator, by analogy to the existing ?.
and *.
operators.
maybe ?|> fun
would propagate nulls from left to right, being equivalent toif (exists _=val) then fun(_) else null
tuple *|> fun
would spread a tuple over the parameters of an arbitrary-arity function, being equivalent tolet (_=val) fun(*_)
(Note that these operators could also be easily defined in terms of |>
and a higher-order function. For example, tuple *|> fun
is equivalent to tuple |> unflatten(fun)
.)
Both of these are useful—I’ve wanted something like ?|>
many times when writing real Ceylon code—but the objection was raised by @someth2say that they’re too ascii-arty for this language. That’s a reasonable objection, and we should give it some weight.
Feedback?
Issue Analytics
- State:
- Created 7 years ago
- Reactions:7
- Comments:91 (74 by maintainers)
Top GitHub Comments
This is now working well enough that you folks can try it out, if you like. For example, the following code:
prints
3C
with bothceylon run
andceylon run-js
.@FroMage My feeling is that we would introduce
|>
as a first step. I don’t think I would add?|>
and*|>
initially, since I kinda agree with the thinking that they’re potentially cryptic.I agree that
bar(foo())
is clearer thanfoo() |> bar
, however, I don’t think that reasoning holds when it’svs