haskell - 按嵌套字段过滤

标签 haskell

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

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/

相关文章:

haskell - 交换列表的前两个元素,(Haskell)

haskell - haskell 中的 `foreach`

haskell - Haskell 中的类型

haskell - 'signum' 在 Haskell 中用于有序数字类型的用例

algorithm - 在 Haskell 中表示计算图

haskell - 无法推导出父类(super class)

haskell - 将数据类型转为String进行显示,不带 `show`

haskell - 在具有多个类型类的自定义数据类型上使用仿函数/应用程序?

unit-testing - IO返回值测试

haskell - 在 JVM 上运行编译为 JavaScript 的 Haskell