计算项目的实例

问题描述

例如输入

["a","b","c","a"]

会导致输出

[("a",2),("b",("c",1)]

我真的想不出一种在 elm 中执行此操作的函数方法

解决方法

使用现有代码是个好主意,但我认为了解这些概念也很有意义:

为了解决需求,您使用递归函数遍历列表并构建中间数据结构。在这种情况下是字典,因为它非常适合计算字符串的出现次数。 然后遍历列表并计算所有元素后,将其转换为元组列表。

https://ellie-app.com/cLBnWHSBj5ta1 上的完整代码

gather : List comparable -> Dict comparable Int -> List ( comparable,Int )
gather list dict =
    case list of
        [] ->
            Dict.toList dict

        first :: rest ->
            let
                count =
                    case Dict.get first dict of
                        Just value ->
                            value + 1

                        Nothing ->
                            1
            in
            Dict.insert first count dict
                |> gather rest

大多数人喜欢在列表中使用 fold 而不是 case-ing,ellie 示例也包含该代码。

但方法是一样的:先解决平凡案例(空列表),然后递归函数,直到遇到平凡案例。

,

如果您可以使用 List.Extra.gatherEquals,那么您只需映射该函数的结果即可满足您的需求:

import List.Extra
List.map (\(x,y) -> (x,1 + List.length y)) (List.Extra.gatherEquals ["a","b","c","a"])
-- [("a",2),("b",("c",1)]