Use a parameter as pattern in Haskell

Viewed 1836

Is it possible to make a generic function that would take either Foo or Bar as an argument and would return a function that uses that argument in its pattern matching?

For instance, if I have

isFoo :: SomeData -> Bool
isFoo (Foo _) = True
isFoo _       = False

isBar :: SomeData -> Bool
isBar (Bar _) = True
isBar _       = False

Is there a way to create a generic function, something like

checkType :: SomeClass -> SomeData -> Bool
checkType (SomeClass _) = True
checkType _ = False

I realize the situation looks a little odd, and the actual use case is a little more complex, but the problem is identical.


The actual code I'm trying to refactor is the following

isString :: [LispVal] -> ThrowsError LispVal
isString [(String _)] = return $ Bool True
isString ((String _):xs) = isString xs >>= unpackBool >>= return . Bool
isString _ = return $ Bool False

isSymbol :: [LispVal] -> ThrowsError LispVal
isSymbol [(Atom _)] = return $ Bool True
isSymbol ((Atom _):xs) = isSymbol xs >>= unpackBool >>= return . Bool
isSymbol _ = return $ Bool False

isNumber :: [LispVal] -> ThrowsError LispVal
isNumber [(Number _)] = return $ Bool True
isNumber ((Number _):xs) = isNumber xs >>= unpackBool >>= return . Bool
isNumber _ = return $ Bool False

So I'd like some way to make this more dry

4 Answers
Related