Can I disable the “non-exhaustive pattern matches”

2019-03-24 18:39发布

Can I disable the non-exhaustive pattern matches warning only for lambdas?

I like the warning in general, but not for actual lambda literals like this:

map (\(x:xs)->...) ls

I think this code makes it pretty clear that I expect all the values of ls to always have at least one element, and there is no neat way to handle the error case in the lambda. (I guess I could move the pattern match into a case statement, but that would just be ugly.)

5条回答
我想做一个坏孩纸
2楼-- · 2019-03-24 19:18

I would go for {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} instead of {-# OPTIONS_GHC -fno-warn-incomplete-uni-patterns #-}. And I would recommend using per-file approach instead of putting it into you cabal file as it is generally good practice to keep getting warnings of this kind.

查看更多
趁早两清
3楼-- · 2019-03-24 19:28

Yes, but only in GHC 7.2 onwards; pass -fno-warn-incomplete-uni-patterns (e.g. in your Cabal file's ghc-options field, or in an {-# OPTIONS_GHC #-} pragma at the top of your file).

However, this will also disable the warning for pattern bindings, so let Just x = Nothing in x won't produce a warning. case statements are unaffected.

查看更多
仙女界的扛把子
4楼-- · 2019-03-24 19:30

In the case of map, you could write this as a list comprehension.

[... | (x:xs) <- ls]

This will not produce any warnings. Although, if an empty list does show up, this will simply filter it out rather than throw an exception, which might conceal errors. Going the type safe route as Ingo suggests might be a better option if you're worried about that.

查看更多
时光不老,我们不散
5楼-- · 2019-03-24 19:34

Do you have such situations quite often? This is a code smell IMHO. I'd like to see some such lambdas and I am quite sure we can make a better version that also handles empty lists quite fine. And in all other cases you might go for a NonEmpty list type wrapper.

查看更多
够拽才男人
6楼-- · 2019-03-24 19:34

You could write

{-# LANGUAGE LambdaCase #-}
map (\case (x:xs)->...; [] -> error "wut") ls

In "wut" you could then describe why that should not have happened.

查看更多
登录 后发表回答