Underline value in case ()

So I saw the syntax for

case () of _ | someBool -> | someOtherBool -> 

I understand what he does, for example. switch the case completely regardless of what is being assessed in the case (which makes sense, since in this case it will be one, and it will always be one).

I also understand that this can and (should) work regardless of the thing being checked in the case (e.g. (1 == 1) (someComplexFunction)), but this block is the fastest.

I don’t quite understand how underline works. He clearly informs the case to completely ignore the contents of the operand and simply check for boolean elements. But where does this operator come from? And in what other contexts can I use it?

+6
source share
1 answer

As @Rhymoid explained in a comment, this is just a coincidence with a template in which nothing is connected and can be replaced with a name (which will be connected). Perhaps it would be more clear to write this as follows:

 case () of _ | someBool -> ... | somOtherBool -> ... 

It can also be written (more or less equivalent) as

 case () of () | someBool -> ... | someOtherBool -> ... 

These are the guards. You may also have protection in a more complex case match:

 case m of Just x | someBool -> ... | someOtherBool -> ... Nothing | someThirdBool -> ... | someFourthBool -> ... 

with as many guards as you want in every match.

The reason for writing the code you pointed out is the trick to get a brief if-then-else style thing with several possibilities. Source code can be better written with the MultiWayIf extension MultiWayIf :

 {-# LANGUAGE MultiWayIf #-} ... if | someBool -> ... | someOtherBool -> ... 

MultiWayIf can also be used with any number of boolean "cases", like the source code.

Underscore can be used in any pattern match for any pattern where you don't need a value later. For instance:

 andBool True True = True andBool _ _ = False 

or

 f (Just _) = 'J' f _ = 'N' 
+12
source

All Articles