Я бы хотел написать функцию, которая принимает оба
и определяет, создано ли данное значение из данного конструктора. Сопоставление с образцом кажется естественным, но сопоставление с образцом должно быть параметром функции, а не жестко заданным именем конструктора.
Приведенный ниже код - это то, что я пробовал, но GHC сообщает о синтаксическом анализе. ошибка в указанной строке.
Есть ли способ сделать это?
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