Reputation: 1304
Suppose I have a structure:
data MyType
= CV Int
| CA MyType MyType
| CI
| CD
| CB
I have a function which expects MyType and I would like to match the following subset of the grammar only:
data MyTypeNoCV
= CA MyType MyType
| CI
| CD
| CB
I know this isn't possible to do in Haskell. Is there a way I would parametrize the structure to somehow tag the nodes?
Could Data.Void possibly help?
Upvotes: 0
Views: 385
Reputation: 1309
The simplest solution is to just split up your data:
data MyTypeNoCV
= CA MyType MyType
| CI
| CD
| CB
data MyType
= CV Int
| CNonV MyTypeNoCV
If you want to be more fancy, you can use GADTs give your data type an index. Here is an example where Ty
is indexed by an Index
.
{-# LANGUAGE DataKinds, GADTs, KindSignatures #-}
data Index = IsBaz | NotBaz
data Ty :: Index -> * where
Foo :: Ty NotBaz
Bar :: Ty NotBaz
Baz :: Ty IsBaz
f :: Ty NotBaz -> Bool
f Foo = True
f Bar = False
Upvotes: 5
Reputation: 4122
If your function is not able to process CV, then it can return Nothing
. Here's a simplified example with just 2 options of data, that might demonstrate what you're looking to accomplish
data MyType = CV | CA
process :: MyType -> Maybe String
process CV = Nothing
process CA = Just "Got CA!"
main = do
putStrLn "Processing CA"
case process CA of
Nothing -> putStrLn "Nothing"
Just x -> putStrLn x
putStrLn "Processing CV"
case process CV of
Nothing -> putStrLn "Nothing"
Just x -> putStrLn x
Then on the command line:
$ runhaskell script.hs
Processing CA
Got CA!
Processing CV
Nothing
Upvotes: 2