Checking for a particular data constructor

后端 未结 3 1120
一整个雨季
一整个雨季 2020-12-18 21:26

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: isMy

3条回答
  •  旧时难觅i
    2020-12-18 21:52

    You can use Maybes. You can create a set of functions that check for each of the types

    getA, getB, getC :: MyData a -> Maybe a
    getA x = case x of {(A v) -> Just v; _ -> Nothing}
    getB x = case x of {(B v) -> Just v; _ -> Nothing}
    getC x = case x of {(C v) -> Just v; _ -> Nothing}
    

    This affords some practical idioms for certain tasks:

    allAs :: [MyData a] -> [a]
    allAs xs = mapMaybe getA xs
    
    printIfA :: Show a => MyData a -> IO ()
    printIfA x = maybe (return ()) print $ getA x
    

提交回复
热议问题