list-extra
list-extra copied to clipboard
Added function: frequencies
Added a new function for calculating the number of occurences in a list for each element in that list.
Cool!
This makes sense. Did you end up needing this function in a project? What was the use case where you needed a frequencies function?
Yes, I needed it while building a game of life simulation app with Elm and I thought there could be numerous cases where one would simply want to retrieve the number of occurences for each element.
The more specific use case for me (in case it is needed) was the following: In a list containing all neighbours of all cells, I count the number of occurences for each neighbour in order to decide what to further do with it.
Please let me know if everything is ok and if more information is needed, thank you!
Is it something like a check that uses data like [ ("occupied", 4), ("unoccupied", 0) ], and then you grab the "occupied" value to see what to do in the game?
I notice the left side of the tuple is supposed to be unique. That makes me think about using a Dict.
That is pretty much it. Use case in more detail: allNeighbours is a list containing the neighbours (all adjacent cells, regardless of their state) for every living/ occupied cell.
allNeighbours : [(Int, Int)]
allNeighbours = ...
Frequencies then groups each unique cell with it`s number of occurences (the relationship of neighborhood being commutative, (x, y) being neighbour to 4 living cells means (x, y) has 4 living cell neighbours.)
freqs = frequencies allNeighbours
Next, we partition this list into living cells and empty cells:
( livingCells, emptyCells ) =
partition (\( x, n ) -> member x list) freqs
And then for each list we filter out survivors/ newborns by how many living cell neighbours they have.
survivors =
filter (\( x, n ) -> n == 2 || n == 3) livingCells
|> List.map Tuple.first
newborns =
filter (\( x, n ) -> n == 3) emptyCells
|> List.map Tuple.first
This was the use case for the frequencies function for me.
I believe this function could be generally quite useful as part of List.Extra.
If everything is in order and this contribution is accepted, please let me know.
That all makes sense. Thank you for your contribution @CristianIorga2000-ops !