I would like to write a function that takes as
- a value constructor for a particular type of algebraic data and
- actual value of the same type
and determines whether the given value is "made from" the given constructor. Matching patterns seems natural for this, but the pattern that should match should have been a function parameter, not a hard-coded constructor name.
Below is the code I tried, but the GHC reports a parsing error on the specified line.
Is there any way to do this?
data FooBar = Foo Int | Bar String
-- Imagine that these are useful functions.
processInt :: Int -> String
processInt = show
processString :: String -> String
processString = id
-- This should take one of the above functions and adapt it to operate on
-- FooBar values of compatible "type". Values that match the given FooBar
-- constructor should be "unwrapped" and passed to the given function.
typeCheck :: (a -> FooBar) -> (a -> String) -> (FooBar -> Maybe String)
typeCheck constructor func fooBar = case fooBar of
(constructor x) -> Just (func x) -- GHC says "Parse error in pattern: constructor"
_ -> Nothing
-- Define processing functions that operate on FooBars.
processFoo :: FooBar -> Maybe String
processFoo = typeCheck Foo processInt
processBar :: FooBar -> Maybe String
processBar = typeCheck Bar processString
source
share