How to create specialized type classes for specific types, the default implementation for other types

I would like to have type types of types that can be added to other types when possible.

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

Now the class will be implemented for some types and for all the others, which I would like to use by default.

How can I do that?

+3
source share
1 answer

It is not necessarily safe or Haskell-y, but it is certainly possible using OverlappingInstances

Turn them on first:

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

Write a casting class:

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

"Optimized" instance:

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

and finally, a common instance for all types:

 instance Castable ab where 

Usage example:

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

By doing this, a default value is selected if the types are not specialized:

 *Main> main Just True Nothing 
+6
source

Source: https://habr.com/ru/post/1270297/


All Articles