list-extra icon indicating copy to clipboard operation
list-extra copied to clipboard

Added function: frequencies

Open CristianIorga2000-ops opened this issue 3 years ago • 4 comments

Added a new function for calculating the number of occurences in a list for each element in that list.

CristianIorga2000-ops avatar Apr 20 '22 09:04 CristianIorga2000-ops

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?

Chadtech avatar May 28 '22 22:05 Chadtech

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!

CristianIorga2000-ops avatar May 30 '22 08:05 CristianIorga2000-ops

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.

Chadtech avatar Jul 10 '22 06:07 Chadtech

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.

CristianIorga2000-ops avatar Jul 12 '22 08:07 CristianIorga2000-ops

That all makes sense. Thank you for your contribution @CristianIorga2000-ops !

Chadtech avatar Oct 31 '22 04:10 Chadtech