【发布时间】:2012-11-29 14:37:01
【问题描述】:
我想写一个同时接受两者的函数
- 某个代数数据类型的值构造函数,以及
- 同一类型的实际值,
并确定给定值是否“由”给定构造函数“制成”。模式匹配似乎很适合这种情况,但要匹配的模式必须是函数参数,而不是硬编码的构造函数名称。
下面的代码是我尝试过的,但是 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
【问题讨论】:
标签: generics haskell pattern-matching