Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

pattern matching - Can I match a data constructor wildcard in Haskell?

I have

data Foo = X (String, Int) | A String | B String | C String | D String -- ...

and have defined

f (X (s, _)) =s 
f (A s) = s
f (B s) = s
f (C s) = s
f (D s) = s
-- ...

but would prefer to be able to write something like

f (X (s, _)) =s 
f (_ s) = s

But there seems to be no way to do this (I get a "parse error" associated with the _).

Is there a way to match a data constructor wildcard in Haskell?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Nope. But you can write this:

data Foo
    = X { name :: String, age :: Int } 
    | A { name :: String }
    | B { name :: String }
    | C { name :: String }
    | D { name :: String }

and then have name :: Foo -> String. You could also consider this:

data Tag = A | B | C | D | X Int
data Foo = Tagged Tag String

f (Tagged _ s) = s

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...