jfmengels / elm-review-simplify

Provides elm-review rules to simplify your Elm code
https://package.elm-lang.org/packages/jfmengels/elm-review-simplify/latest/
BSD 3-Clause "New" or "Revised" License
20 stars 9 forks source link

many more repeat simplifications #304

Open lue-bird opened 3 months ago

lue-bird commented 3 months ago
List.member needle (List.repeat n a)
-->
(n >= 1) -- if determined True, only right
    && (a == needle) -- if determined equal, only left
    -- and if both are determined True, return True

List.any f needle (List.repeat n a)
-->
(n >= 1) -- if determined True, only right
    && (f a)

List.all f needle (List.repeat n a)
-->
(n <= 0)-- if determined True, only right
    || (f a)

List.head (List.repeat n a) -- same with minimum, maximum
-->
if n <= 0 then -- if determined True, only else
    Nothing

else
    Just a

List.filter f (List.repeat n a)
-->
if f a then
    List.repeat n a

else
    []

List.sum (List.repeat n a)
--> (Basics.max 0 n) * a

List.product (List.repeat n a)
--> a ^ (Basics.max 0 n)

List.reverse (List.repeat n a) -- same with sort, sortBy f, sortWith f
--> List.repeat n a

for Array:

Array.get i (Array.repeat n a)
-->
if i >= 0 && i < n then
    Just a

else
    Nothing

Array.filter f (Array.repeat n a)
-->
if f a then
    Array.repeat n a

else
    []

likely controversial

List.unzip (List.repeat n ( a, b ))
--> ( List.repeat n a, List.repeat n b )

because if n is not simple, logic gets unnecessarily duplicated.

List.filterMap f (List.repeat n a)
--> Maybe.withDefault [] (Maybe.map (List.repeat n) (f a))

because while it's technically simpler logic-wise and much more performant the resulting code looks ugly (to me).

jfmengels commented 3 months ago

I like these simplifications!

The List.reverse one just makes a lot of sense in particular :+1:

There are however a few ones that I think we probably shouldn't do, and those are the ones where we end up repeat n or f or a. While it looks good in small examples like these, these could be large expressions, and you end up with the code duplication (just like you mentioned for List.unzip) which then makes maintenance potentially harder.

List.filterMap f (List.repeat n a)

It does look quite a big uglier yeah...