elm-format icon indicating copy to clipboard operation
elm-format copied to clipboard

Rewrite `[ foo ] ++ bar` to `foo :: bar`?

Open rtfeldman opened this issue 8 years ago • 4 comments

elm-analyse gives a warning for this situation:

If you concatenate two lists, but the [left hand side is a single element list literal], then you should use the cons operator.

This seems like not only a stylistic concern, but a performance optimization!

I can't think of any situations where it would be better to write e.g. [ foo ] ++ anyOtherList than foo :: anyOtherList. Should elm-format automatically perform this rewrite?

rtfeldman avatar Sep 02 '17 21:09 rtfeldman

What about the following line:

oneList ++ [ oneItem ] ++ anotherList

From a purely stylistic point of view I think it looks nicer than:

oneList ++ (oneItem :: anotherList)

I assumed the elm compiler would optimise the second append, but I guess if it doesn't, maybe style doesn't matter as much.

Now even if we do want the optimised version, is it really the role of elm-format to apply this change?

basile-henry avatar Sep 03 '17 16:09 basile-henry

@basile-henry Actually, since (++) and (::) are both right associative and have the same precedence (source), the parentheses are superfluous and, if that feature sticks, will be automatically removed by elm-format, so the end code would be

oneList ++ oneItem :: anotherItem

I'm not sure whether that is stylistically better or worse than the first alternative. I do share your concern whether this is elm-format's area of responsibility though.

ahstro avatar Oct 24 '17 19:10 ahstro

I'd vote against this. Symmetry in code is useful for readability, so having both [a] ++ b and b ++ [a] is more readable, symmetry-wise, than replacing it with ::. This optimisation should be trivial to add to the compiler if anyone wants to take a stab at it.

drathier avatar Nov 19 '18 13:11 drathier

Not to dig up a very old issue, but elm-review-simplify now does this transformation.

Screenshot from 2021-04-28 09-36-28

elm-review then applies elm-format so it removes the extra parens is they prove to not be needed.

I don't know if I would have liked elm-format to do this change, but at least it's available somewhere, and people can choose not to opt-in if they don't like it.

jfmengels avatar Apr 28 '21 07:04 jfmengels