如何获取具有最多属性值的项目?

时间:2017-11-12 13:18:49

标签: elm

我有一个记录列表,这些记录偶尔可以与列表中的其他记录具有相同的属性值。

我想确定属性值的最高位置。

这样的记录可以是以下内容:

type alias Topic =
    { name : String }

我相信为了实现这一目标,我需要使用List.groupBy

结果,我尝试了以下内容:

topicGroups =
        |> someTopics
        |> List.map .name
        |> groupWhile (\name1 name2 -> name1 == name2)

orderedTopics =
    topicGroups
        |> List.sortBy List.length
        |> List.reverse
        |> List.concat
        |> uniqueBy toString
        |> List.map (\n -> { name = n })

但是上面的代码对我来说并不适合。它似乎按降序返回所有主题。

可以找到源代码here

1 个答案:

答案 0 :(得分:1)

当我在Repl

中尝试它时,它看起来会起作用
module Test exposing (..)

import List as L
import Dict exposing (Dict)


type alias Topic =
    { name : String }


mostCommon : List Topic -> Maybe String
mostCommon lst =
    let
        incrementer : Maybe Int -> Maybe Int
        incrementer mbIdx =
            mbIdx |> Maybe.map ((+) 1) |> Maybe.withDefault 1 |> Just

        go : Topic -> Dict String Int -> Dict String Int
        go t acc =
            Dict.update t.name incrementer acc
    in
        L.foldl go Dict.empty lst
            |> Dict.toList
            |> List.sortBy (Tuple.second >> (*) -1)
            |> L.head
            |> Maybe.map Tuple.first


myMax =
    mostCommon [ Topic "a", Topic "b", Topic "a", Topic "b", Topic "b" ]
相关问题