sweet-js / sweet-core

Sweeten your JavaScript.
https://www.sweetjs.org
BSD 2-Clause "Simplified" License
4.58k stars 208 forks source link

Implement custom operators #665

Closed disnet closed 7 years ago

disnet commented 7 years ago

Fixes #517.

Easier than I thought it would be.

I chose to go with using the same declarator form that syntax and syntaxrec use. Made the implementation much simpler than other forms since it can just piggyback on the work done for syntax/syntaxrec in terms of binding and loading into the compiletime env.

It's not the most user-friendly syntactic form but we can always provide a macro the give some sugar (I suspect a declaration form would work nicely but we can play with that later).

I've just implemented binary and prefix unary. Postfix unary requires a few more changes that I'd like to do later.

operator >>= left 3 = (left, right) => {
  return #`${left}.chain(${right})`;
}
class IdMonad {
  constructor(value) {
    this.value = value;
  }
  chain(f) {
    return f(this.value);
  }
}

function Id(value) {
  return new IdMonad(value);
}

let result = Id(1) >>= v => Id(v + 1)
                   >>= v => Id(v * 10);
disnet commented 7 years ago

Postfix unary requires a few more changes that I'd like to do later.

Actually postfix was straightforward too so I'll include that in this PR too.