Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...