问题描述
假设我定义了自己的数据类型,如
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).
这篇关于检查特定的数据构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!