![](/img/trans.png)
[英]Is it possible to have an if function use pattern matching in Haskell?
[英]Is it possible in Haskell to write the catch-all pattern first? Or use “negative” pattern?
有時,如果模式規則需要一些特殊的 rhs,通過where
使其更具可讀性,我最終會得到這樣的結果
data D = A | B | C
func :: D -> b
func A = special_case
where
special_case = other helper
other = aaaa
helper = bbb
func _ = bla
where 包羅萬象的模式似乎與其他模式相去甚遠,因為where
很長。 如果我能寫出這樣的東西就好了:
func :: D -> b
func !A = bla -- imaginary syntax
func A = special_case
where
special_case = other helper
other = aaaa
helper = bbb
我認為它仍然不會被稱為包羅萬象,而是“包羅萬象”,但是有什么辦法可以做到這一點嗎?
如果你不需要綁定任何東西,你可以這樣做:
isA :: D -> Bool
isA A = True
isA _ = False
func :: D -> b
func d | not (isA d) = bla
func A = special_case where ...
(您可以交替實現isn'tA
來避免not
。但是,雖然我經常看到像isA
這樣定義的函數,但我不相信我曾經在野外見過isn'tA
的類似物。)
對於編譯器來說,這個匹配是否完整可能並不明顯。 你可以像這樣解決這個問題:
type A'sFields = () -- your specific D doesn't have any fields for A,
-- but this pattern is general enough to use for
-- constructors that do
fromA :: D -> Maybe A'sFields
fromA A = Just ()
fromA _ = Nothing
func :: D -> b
func d = case fromA d of
Nothing -> bla
Just () -> special_case where ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.