decisionpatterns / backpipe

Backward (right-to-left) Pipe Operator
Other
30 stars 1 forks source link

Document uses #1

Open ctbrown opened 7 years ago

ctbrown commented 7 years ago

An interesting use of backpipe is when it is used to clear some clutter. Two uses come to mind.

This makes them more like the way that if works.

#' ## S4 Methods
setMethod( "cx", signature("character","character"), . ) %:% 
  function(x,y) { print("hw") } 

#' ## Logging
 warn %:% "This is not a love song"

There are some variants of this. For example, you could backwardly create a list of arguments that are then passed to the first argument ... always a function.

warn %:% "you've been warned" %:% immediate=TRUE 

Even better if we can give it a special operator:

warn : "you've been warned" 
mutahiwachira commented 1 year ago

Many years later, but did you ever consider using the backpipe to provide syntax matching the mathematical style for 'where'? As in, "let y = f(x) where f(x) is the sine function"

At the time of writing this comment, the backpipe is %<%. So look at this:

`%where%` <- `%<%`

x <- 5
z <- 
  {cube(x)} %where%
  {cube = \(x) x*x*x}

Read it as, "Let x = 5. z is the cube of, where cube means xxx"

I am experimenting with some very heavy use of anonymous functions. I find it weird to read code where I first define the anonymous function and give it a name and then call it. It adds mental overhead and I think it is much more reasonable to say

result <- nicely_named_op(input) %where%
  nicely_named_op = \(x) # ugly set of function calls

I would really like to be able to write

x_turning_point = min_point(parabola) %where%
  {min_point = \(a,b,c) -b/2*a}

Not that this would be useful or good for production code necessarily. But it could be fun.