Haskell:是否可以在模式匹配中使用抽象数据类型

Joe*_*Joe -1 haskell pattern-matching adt

假设我有一个名为foo的ADT

data foo = N Integer | V Var | Div foo foo
Run Code Online (Sandbox Code Playgroud)

有没有办法在模式匹配中使用ADT,所以我不必写出每种可能的数据类型组合?

myfunc :: foo -> [Var]
myfunc (N _) = []
myfunc (V a) = [a]
myfunc (Div (foo) (foo)) = myfunc(foo) ++ myfunc(foo)
Run Code Online (Sandbox Code Playgroud)

有没有办法做这样的工作,所以我不必写

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)
...
Run Code Online (Sandbox Code Playgroud)

等等

bhe*_*ilr 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
Run Code Online (Sandbox Code Playgroud)

去测试:

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"]
Run Code Online (Sandbox Code Playgroud)