过滤列表中的索引

时间:2018-09-16 19:59:35

标签: elm

我需要从2D列表中过滤出空位置,但只能在获取了 后返回索引列表,这意味着索引已不再与这些索引匹配位置曾经是2D数组的一部分。

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

我需要的是[1, 2, 5, 7, 8],因为openPositionIndexes不是[0,1,2,3,4],因为这些索引是错误的,它们基于过滤 list结果,而不是在list数组中找到原始索引。

1 个答案:

答案 0 :(得分:2)

您必须首先通过List.indexedMap运行它,然后将索引和值一起保存以备后用。在这里,我将它们打包成一个元组:

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

或使用记录:

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