Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make specialized type classes for certain types, default implementation for the rest of types

I would like to have a type class of types that can possibly casted to other types when possible.

class Castable a b where  
    cast :: a -> Maybe b  
    cast _ = Nothing -- default implementation  

Now the class would be implemented for some types and for all the others I would like to have default implementation.

How one can do that?

like image 906
Tener Avatar asked Nov 20 '25 22:11

Tener


1 Answers

It's not necessarily a safe or Haskell-y thing to do, but it is certainly possible, using OverlappingInstances

First, enable them:

{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances     #-}
{-# LANGUAGE OverlappingInstances  #-}

Write your casting class:

class Castable a b where  
    cast :: a -> Maybe b  
    cast _ = Nothing -- default implementation  

An "optimized" instance:

instance Castable Int Bool where
        cast 0 = Just False
        cast _ = Just True

and finally, a general instance for all types:

instance Castable a b where

Example use:

main = do
    print $ (cast (7 :: Int) :: Maybe Bool)
    print $ (cast (7 :: Int) :: Maybe Integer)

Running this, the default is chosen when the types aren't specialized:

*Main> main
Just True
Nothing
like image 94
Don Stewart Avatar answered Nov 23 '25 12:11

Don Stewart



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!