← Back to context

Comment by bunderbunder

3 days ago

One of the things I love about programming in dialects of ML like ocaml and f# is the forward pipe operator:

  x
  |> f
  |> g
  |> h

It's nice because it just puts whatever's on the left of the operator in as the last argument. So it also works for functions with an arity of more than one.

So if it were something like

  h(z, g(y, f(x))

you can write it as

  x
  |> f
  |> g y
  |> h z

It works really nicely for data munging code:

  my_data
  |> filter (x => x > 37)
  |> select (x => x * 2)
  |> sum

but unlike doing it with method calls in object oriented code, inserting a new function into the chain doesn't involve modifying a class or or mucking around with more complex language features like extension methods and traits.

There's also function composition

   (h . g . f) x

Or for LtR, with Control.Category

   (f >>> g >>> h) x

Could combine with the forward pipe for

   x |> (f >>> g >>> h)

Lisp macros let you do similar things, and you don't have to change the language itself.

  • In ML family languages you also don't have to change the language for this, as function application is naturally "argument-by-argument" (the term is "curried"): the syntax is normally f x y z but (f x y) z and (((f)) (x)) y z are just as valid, and indeed f x y will be a function taking one argument. Thus |> can just take a function of one argument and be done.

  • Maybe I've just been doing too much Racket lately and that's affecting how I view things, but it's real hard for me to not think of lisp macros as a mechanism for changing the language itself. Especially if it's something like a reader macro.

    • A lot of Common Lisp is like this. They took things that were used to implement standard parts of the language, and went "you know, users might also want to have these", and exposed them as part of the standard. If I were to extend Common Lisp I'd standardize and expose more things like this.

  • You could say the same about more or less any language feature - the thing is though that having a standard feature people can agree on is better than several people’s divergent opinions on which macros are sufficiently aesthetically pleasing.