开发者

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

开发者 https://www.devze.com 2023-02-23 01:18 出处:网络
I would like to have a type class of types that can possibly casted to other types when possible. class Castable a b where

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 开发者_如何学JAVAdo that?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消