Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pattern match different ways depending on a particular input?

I have a function:

closeTo61 :: Tactic
closeTo61 s P2 h d e b 
    | cs + ps < 53 = 0
    | cs + ps == 61 = 100 -- Best case
    | numWaysToScoreN (61 - (cs + ps)) h b == 0 = 0 -- Worst case
    | numWaysToScoreN (61 - (cs + ps)) h b == 1 = 50 -- Strong case
    | numWaysToScoreN (61 - (cs + ps)) h b == 2 = 70 -- Very Strong case
    | numWaysToScoreN (61 - (cs + ps)) h b >= 3 = 90 -- Extremely Strong case
        where 
            ps = scoreDom d e b
            (_,cs) = s

closeTo61 s P1 h d e b 
    | cs + ps < 53 = 0
    | cs + ps == 61 = 100
    | numWaysToScoreN (61 - (cs + ps)) h b == 0 = 0
    | numWaysToScoreN (61 - (cs + ps)) h b == 1 = 50
    | numWaysToScoreN (61 - (cs + ps)) h b == 2 = 70
    | numWaysToScoreN (61 - (cs + ps)) h b >= 3 = 90
        where 
            ps = scoreDom d e b
            (cs,_) = s

The only reason I've done this with two bindings for each possible input of the second argument is because in the where block the cs is pattern matched differently depending on this input.

Is there a way to do this using only one binding and checking the second input inside the where block in order to use the correct pattern?

like image 819
Charles Del Lar Avatar asked Dec 05 '25 09:12

Charles Del Lar


2 Answers

You could instead do

closeTo61 s p h d e b
    | cs + ps < 53 = 0
    | ...
    where
        cs = chooseByP p s
        chooseByP P1 = fst
        chooseByP P2 = snd

Although, since you only use s and p to determine which element of s to use, why have them as separate arguments here?

closeTo61 cs h d e b
    | ...
    where
        ps = scoreDom d e b

closeTo61' s p = closeTo61 (chooseByP p s)
like image 118
bheklilr Avatar answered Dec 07 '25 22:12

bheklilr


You can move the pattern match into the where block where you define cs:

closeTo61 s p h d e b 
   ...
   where cs = case p of P1 -> fst s; P2 -> snd s

If you do this a lot (and, since you defined a type for P1 and P2, you might be), I would extract this logic into a more meaningful helper function:

component P1 (x, _) = x
component P2 (_, x) = x

Then you can do

 closeTo61 s p h d e b 
   ...
   where cs = component p s
like image 31
Tikhon Jelvis Avatar answered Dec 08 '25 00:12

Tikhon Jelvis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!