Pipe operator
I can't stop thinking about this feature after merge the with
keyword from @nschrader.
42 |> foo() |> bar same as bar(foo(42))
We already have several features from functional languages, and I think this one is particularly good.
It works just as UFSC but with special operator, not just .
Having a special operator instead of a dot is better for two reasons: first, better readability, and second, better support for auto-completion.
For example, because of UFSC in Nim, it is impossible to understand which functions this has, and which are autocompleted due to the signature match for UFSC, because methods are suggested that have the same type as the first argument of the variable that I call autocompletion for.
Real code example
So here are 2 code examples that demonstrate better readability when using the pipe operator:
const double DEG = 57.29577951308232;
const int CX = 130;
const int CY = -130;
double get_clock_value_by_coords(double step, double x, double y){
double atan = Math.atan2(CY, CX) - Math.atan2(y, x);
var deg = atan * DEG;
deg = Math.round(deg / step) * step;
deg %= 360;
return Math.floor(deg / step);
}
//////////////////////////////
double get_circle_arctangent_andgle(double x, double y, double center_x = CX, double center_y = CY){
return Math.atan2(CY, CX) - Math.atan2(y, x);
}
double round_degree_according_to_step (double deg, double step){
return Math.round(deg / step) * step;
}
double modulo(double a, double b){
return a %= b;
}
double rad2deg(double rad){
return rad * DEG;
}
double get_clock_value_by_coords2(double step, double x, double y){
return get_circle_arctangent_andgle(x, y)
|> rad2deg()
|> round_degree_according_to_step(step)
|> modulo(360)
|> (clockValue => clockValue / step)
}
I am sure that this is not the best example, but looking at the second one a year later, it will become clearer much faster how it works.
The pipe operator can be an alternative to extension methods feature from C#:
int char_count(string str, char c){
int counter = 0;
for (int i = 0; i<str.length; i++){
if (str[i] == c)
counter++;
}
return counter;
}
...
int count = "Hello World" |> char_count('l');