satyr / coco

Unfancy CoffeeScript
http://satyr.github.com/coco/
MIT License
498 stars 48 forks source link

"Truthy pipe" syntax proposition #197

Closed akx closed 11 years ago

akx commented 11 years ago

For a lark, I wanted to see what some Django ORM code might look like in Coco and ended up with

object-list =
  Category.objects.language instance.language
  |> if category = instance.category then &filter {category} else &
  |> &slice instance.count

-- this works alright, but the second line of the chain is kinda ugly because of the else branch.

So I'd propose a "truthy pipe" syntax, perhaps ?>, so any falsy values in that block would be emitted as & instead.

object-list =
  Category.objects.language instance.language
  ?> (&filter {category} if category = instance.category)
  |> &slice instance.count

Currently, with Coco 0.9, with |> instead of ?> the following JS is emitted (I've added some linebreaks for readability), and obviously the "void 8" emitted as the implicit "else" breaks the chaining.

var objectList, x$, category;
objectList = (
  x$ = Category.objects.language(instance.language),
  x$ = (category = instance.category) ?
    x$.filter({category: category}) :
    void 8,
  x$.slice(instance.count)
);

In addition I wouldn't mind it if ?> had a slightly different precedence so the parentheses in the post-if wouldn't be necessary...

satyr commented 11 years ago

A new operator solely for omitting at most 7 bytes in a narrow situation sounds overkill.

satyr commented 11 years ago

Closing for the reason above.

I wouldn't mind it if ?> had a slightly different precedence so the parentheses in the post-if wouldn't be necessary...

As for this issue, |> is given the lowest precedence present (as I didn't want to create yet another level) which happens to be the same as post-if. May have been a mistake considering expressions like a |> b if c |> d unintuitively evaluates as ((a |> b) if c) |> d.

vendethiel commented 11 years ago

On a single line, isn't it going to conflict with post-if specialcase ?

satyr commented 11 years ago

What specialcase exactly?

vendethiel commented 11 years ago

I'm talking about inline implicit object rule (something like that), 140c648.

satyr commented 11 years ago

The brace-insertion for implicit objects kicks in before the parser job. They may seem to interact oddly, but not in a conflicting way.

vendethiel commented 11 years ago

I don't really get what happens in cases like a |> b c: d |> foo if bar.

satyr commented 11 years ago

It goes:

a |> b {c: d |> foo} if bar

a |> b({c: d |> foo}) if bar

a |> (b({c: d |> foo}) if bar)

Hm. Probably |> should also close inline implicit objects.

vendethiel commented 11 years ago

Yeah, that's what I thought.