gpt4 book ai didi

haskell - 测试一个值是否与构造函数匹配

转载 作者:行者123 更新时间:2023-12-03 07:25:37 25 4
gpt4 key购买 nike

假设我有这样的数据类型:

data NumCol = Empty |
Single Int |
Pair Int Int |
Lots [Int]

现在我希望从 [NumCol] 中过滤出与给定构造函数匹配的元素。我可以为Pair编写它:

get_pairs :: [NumCol] -> [NumCol]
get_pairs = filter is_pair
where is_pair (Pair _ _) = True
is_pair _ = False

这可行,但不是通用的。我必须为 is_singleis_lots 等编写一个单独的函数。

我希望我可以写:

get_pairs = filter (== Pair)

但这仅适用于不带参数的类型构造函数(即Empty)。

所以问题是,如何编写一个函数,它接受一个值和一个构造函数,并返回该值是否与构造函数匹配?

最佳答案

至少 get_pairs 本身可以通过使用列表理解来过滤来相对简单地定义:

get_pairs xs = [x | x@Pair {} <- xs]

对于匹配构造函数的更通用的解决方案,您可以使用 lens 包中的棱镜:

{-# LANGUAGE TemplateHaskell #-}

import Control.Lens
import Control.Lens.Extras (is)

data NumCol = Empty |
Single Int |
Pair Int Int |
Lots [Int]

-- Uses Template Haskell to create the Prisms _Empty, _Single, _Pair and _Lots
-- corresponding to your constructors
makePrisms ''NumCol

get_pairs :: [NumCol] -> [NumCol]
get_pairs = filter (is _Pair)

关于haskell - 测试一个值是否与构造函数匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25587501/

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