elm-community / webgl

Moved to elm-explorations/webgl
https://package.elm-lang.org/packages/elm-explorations/webgl/latest
BSD 3-Clause "New" or "Revised" License
131 stars 18 forks source link

WebGL iterates with List.map that reverses the order #12

Closed w0rm closed 7 years ago

w0rm commented 7 years ago

I've discovered that WebGL uses List.map in order to iterate over lists. Unfortunately this reverses the order of the elements, so we have to additionally call List.reverse. This seems to be a waste of cpu cycles.

Is there a better way to iterate over lists in the Native land?

fredcy commented 7 years ago

Maybe you could use List.foldr to define an order-preserving map.

mapr fn = List.foldr (\x a -> fn x :: a) []

w0rm commented 7 years ago

@fredcy I just need to preserve the order of iteration and I don't need to build a new list. List.map is built with List.foldr so the iteration happens backwards because this is how we construct lists.

I guess List.foldl should work for me, will try it

w0rm commented 7 years ago

Yeah, List.foldl is better than List.map for the webgl, it is iterating over list only once, while List.map builds unnecessary output, and iterates over the list twice (because List.foldrconverts list to array and then iterates over it in the reverse order).

w0rm commented 7 years ago

This worked for #8

w0rm commented 7 years ago

Answering @eeue56 here

I took a look through, and there's a bunch of places where you would be better off writing a function to iterate through the list as you intend yourself. You don't get much benefit from using core's foldl if you're using it in an impure way, and it would be simpler to follow without it

I think that the benefit from using foldl over traversing the internal representation of list is that if the internal representation of a list changes, then WebGL code won't be affected.

eeue56 commented 7 years ago

The internal representation of List hasn't changed for years. Other libraries, such as the virtual-dom, also use their own function for unwrapping lists.

Introducing things like undefined in order to re-use a core function is not really a good idea. Just define the function you need yourself and use that. It'll be faster too, without the A3 call.

w0rm commented 7 years ago

@eeue56 ok, will do as you suggested