说我有一个名为foo的ADT
data foo = N Integer | V Var | Div foo foo
有没有办法在模式匹配中使用ADT,所以我不必写出每种可能的数据类型组合?
myfunc :: foo -> [Var]
myfunc (N _) = []
myfunc (V a) = [a]
myfunc (Div (foo) (foo)) = myfunc(foo) ++ myfunc(foo)
有没有办法制作类似这样的作品,所以我不必写
myfunc (Div (N a) (N b)) = myfunc(N a) ++ myfunc(N b)
myfunc (Div (V a) (N b)) = myfunc(V a) ++ myfunc(N b)
myfunc (Div (N a) (V b)) = myfunc(N a) ++ myfunc(V b)
...
等
答案 0 :(得分:11)
好吧,如果你说出正确的名字,你的作品是什么:
-- types have to begin with a capital letter, just like constructors
data Foo = N Integer | V Var | Div Foo Foo
myfunc :: Foo -> [Var]
myfunc (N _) = []
myfunc (V a) = [a]
myfunc (Div left right) = myfunc left ++ myfunc right
测试:
type Var = String -- Don't know what Var is, but it's a String for this example
> myfunc (Div (Div (V "A") (V "B")) (Div (V "C") (N 1)))
["A", "B", "C"]