检查特定的数据构造函数 [英] Checking for a particular data constructor

查看:109
本文介绍了检查特定的数据构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我定义了自己的数据类型,如

  data MyData = A arg | B arg2 | C arg3 

如何编写函数(例如: isMyDataType ),它检查给定参数是否来自 MyData 中特定类型的参数,并连续返回一个布尔值(True或False),例如输入Ghci:
isMyDataType B 返回True并且 isMyDataType Int 返回False。

解决方案

我相信你需要函数来测试特定的构造函数

  isA :: MyData  - > Bool 
isB :: MyData - > Bool

如果是这样,那么您可以自己编写或派生它们。实现将如下所示:

  isA(A _)= True 
isA _ = False

isB(B_)= True
isB _ = False

为了推导它们自动,只需使用派生库并在源代码中添加:

  { - #LANGUAGE TemplateHaskell# - } 
导入Data.DeriveTH

data MyData = ...
导出(Eq,Ord,Show)

派生make''MyData
- 较老的GHCs需要更多的语法:$(derive makeIs''MyData)

另请注意:您的数据声明无效,名称必须大写, MyData 代替 myData



最后,这整个答案是基于你想测试构造函数的假设,不是你说的数据类型(在编译时静态检查,正如Tarrasch所说)。

Let's say that I defined my own data-Type like

data MyData = A arg| B arg2| C arg3

How would I write a function (for instance: isMyDataType) that checks wether the given argument is one out of the particular types in MyData and successively returns a boolean (True or False) , e.g. typing in Ghci: isMyDataType B returns True and isMyDataType Int returns False.

解决方案

I believe you want functions to test for particular constructors:

isA :: MyData -> Bool
isB :: MyData -> Bool

If so, then you can write these yourself or derive them. The implementation would look like:

isA (A _) = True
isA _     = False

isB (B _) = True
isB _     = False

To derive them automatically, just use the derive library and add, in your source code:

{-# LANGUAGE TemplateHaskell #-}
import Data.DeriveTH

data MyData = ...
    deriving (Eq, Ord, Show}

derive makeIs ''MyData
-- Older GHCs require more syntax: $( derive makeIs ''MyData)

Also note: your data declaration is invalid, the name must be capitalized, MyData instead of myData.

Finally, this whole answer is based on the assumption you want to test constructors, not data types as you said (which are statically checked at compile time, as Tarrasch said).

这篇关于检查特定的数据构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆