gpt4 book ai didi

haskell - 按嵌套字段过滤

转载 作者:行者123 更新时间:2023-12-02 12:08:10 25 4
gpt4 key购买 nike

我的汽车类型有一个子类型“零件”:

data Part =
Part
{ currency :: Text
, value :: Float
}
deriving (Generic, Show)

data Car =
Car
{ brand :: Text
, engine :: Part
}
deriving (Generic, Show)

我正在尝试访问并调整汽车列表,如下所示:

filterByEnginePrice :: [Car] -> Float -> [Car]
filterByEnginePrice cars threshold =
Prelude.filter (\car -> engine car <= threshold) cars

但是,GHC 给了我以下错误:

 • Couldn't match expected type ‘Part’ with actual type ‘Float’

这是有道理的,因为我想按而不是部分进行过滤。访问过滤器函数中的 value 字段的语法是什么?

最佳答案

您可以使用value::Part -> Float getter 获取值:

filterByEnginePrice :: [Car] -> Float -> [Car]
filterByEnginePrice cars threshold = Prelude.filter (\car -> <b>value (</b>engine car<b>)</b> <= threshold) cars

但更惯用的做法是在 lambda 表达式的头部“解压”数据构造函数:

filterByEnginePrice :: [Car] -> Float -> [Car]
filterByEnginePrice cars threshold = Prelude.filter (\<b>Car { engine=Part {value=v} }</b> -> <b>v</b> <= threshold) cars

或者我们可以使用无点表达式,如 @oisdk 指定的:

filterByEnginePrice :: [Car] -> Float -> [Car]
filterByEnginePrice cars threshold = Prelude.filter ((<b>threshold >=</b>) . value . engine) cars

关于haskell - 按嵌套字段过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60695725/

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