gpt4 book ai didi

elm - 如何从列表中获取不同的项目?

转载 作者:行者123 更新时间:2023-12-01 23:16:22 24 4
gpt4 key购买 nike

我不清楚如何从列表中检索不同的项目。

我有以下代码:

topicsFromLinks : List Link -> List Topic
topicsFromLinks links =
links
|> List.map (\l -> l.topics)
|> List.concat
|> Set.fromList
|> Set.toList

错误:

The definition of topicsFromLinks does not match its type annotation. - The type annotation for topicsFromLinks says it always returns:

List Topic

But the returned value (shown above) is a:

List comparable


我希望以下几行仅适用于结构平等:
|> Set.fromList
|> Set.toList

为什么我会收到可比项目列表?

如何解决此编译错误?

附录:
type alias Topic =
{ name : String, isFeatured : Bool }

type alias Link =
{
...
, topics : List Topic
...
}

最佳答案

根据 documentation for Set :

The values can be any comparable type. This includes Int, Float, Time, Char, String, and tuples or lists of comparable types.



您正在尝试将 Topic 值放入只有可比较类型才能工作的位置。

值得庆幸的是,有 elm-community/list-extra 包,它公开了一个 uniqueBy 函数,可以让你指定自己的函数来将某些东西变成可比较的。

如果您想获得不同的主题列表,同时匹配 nameisFeatured 字段,那么您可以使用 toString 将值序列化为类似的内容:

import List.Extra exposing (uniqueBy)

topicsFromLinks : List Link -> List Topic
topicsFromLinks links =
links
|> List.map .topics
|> List.concat
|> uniqueBy toString

关于elm - 如何从列表中获取不同的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47223326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com