[英]Haskell: Is it possible to use the abstract data type in pattern matching
假設我有一個稱為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)
...
等等
好吧,如果您正確命名事物,那么您所擁有的將起作用:
-- 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"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.