Bool class - like Num?

I have my type:

data MyType = ...

Now I would like to use a value of this type in if. Is it possible to implement it? Of course, at this moment I get the error:

 Couldn't match expected type ‘Bool’ with actual type ‘MyType’
+4
source share
2 answers

Standard semantics if/ then/ is elsecharacteristic of Bool. Using GHC, you can change the standard semantics using the extension RebindableSyntax. Quoting from documents:

... the flag -XRebindableSyntaxforces the following parts of the built-in syntax to refer to everything in scope and not to the version Prelude:

  • Symbols (e.g. if e1 then e2 else e3) mean ifThenElse e1 e2 e3. However, expressions are casenot affected.

.

, . MyType -> Bool; if predicate myValue then ... else .... , , ; , , - .

+7

, -XRebindableSyntax ( ):

{-# LANGUAGE RebindableSyntax #-}
module Test where

import qualified Prelude as P


class Decidable b where
    toBool :: b -> P.Bool

instance Decidable P.Bool where
    toBool = P.id

ifThenElse :: Decidable b => b -> a -> a -> a
ifThenElse b ifTrue ifFalse = case toBool b of
    P.True -> ifTrue
    P.False -> ifFalse

data Test = A | B deriving (P.Eq, P.Show)

instance Decidable Test where
    toBool A = P.True
    toBool B = P.False

GHCi:

> :l decidable.hs
> :set -XRebindableSyntax
> P.putStrLn (if A then "it worked!" else "it failed!")
it worked!

, ! , - , , , .

+1

All Articles