Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'pattern matching' on Typeable types

Suppose, for example, we have the following data structure:

data Foo = Bool Bool | Int Int | Double Double

Now, is there an easier way to do this:

foo :: Typeable a => a -> Foo
foo x = maybe (error "i dunno") id $
  liftM Bool   (cast x) `mplus`
  liftM Int    (cast x) `mplus`
  liftM Double (cast x)

Has someone thought of making a syntax for pattern matching on Typeable types?


1 Answers

Use typeOf and guards:

foo x
    | tx == typeOf "str" = "string"
    | tx == typeOf True  = "bool"
    | otherwise          = "i dunno"
  where tx = typeOf x
like image 108
sclv Avatar answered Mar 04 '26 18:03

sclv



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!