PositiveGuy
PositiveGuy

Reputation: 20202

Filter out Indexes in List

I need to filter out empty positions from this 2D List but have only been able to get a list back of indexes after it's been filtered already which means the indexes no longer match up to the indexes these positions had when they were once part of the 2D array.

list :: List Char
list = ['X',' ',' ','O','O',' ','X',' ',' ']

openPositionIndexes = List.filter (\pos -> pos == empty) list
    |> (List.indexedMap (\i pos -> i))
-- [0,1,2,3,4] : List Int

what I need is [1, 2, 5, 7, 8] as the openPositionIndexes not [0,1,2,3,4] because those indexes are wrong, they're based on the filtered list result, not the original indexes found in list array.

Upvotes: 0

Views: 313

Answers (1)

glennsl
glennsl

Reputation: 29106

You'll have to run it through List.indexedMap first, then save the index along with the value for later use. Here I pack them together in a tuple:

openPositionIndexes =
    list
        |> List.indexedMap (\i cell -> ( i, cell ))
        |> List.filter (\( _, cell ) -> cell == empty)
        |> List.map Tuple.first

Or using a record:

openPositionIndexes =
    list
        |> List.indexedMap (\i cell -> { index = i, cell = cell })
        |> List.filter (\{ cell } -> cell == empty)
        |> List.map .index

Upvotes: 2

Related Questions