如何获取 属性 值出现次数最多的项目?
How do I get items with the most occurrences of a property value?
我有一个记录列表,偶尔可以与列表中的其他记录具有相同的 属性 值。
我想确定出现次数最多的 属性 值。
这样的记录可以是:
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 })
但是上面的代码对我不起作用。它似乎 return 所有主题都按降序排列。
可以找到源代码here。
当我在 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" ]
我有一个记录列表,偶尔可以与列表中的其他记录具有相同的 属性 值。
我想确定出现次数最多的 属性 值。
这样的记录可以是:
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 })
但是上面的代码对我不起作用。它似乎 return 所有主题都按降序排列。
可以找到源代码here。
当我在 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" ]