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

杀马特。学长 韩版系。学妹 提交于 2020-01-13 17:56:09

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/5607372/how-to-make-specialized-type-classes-for-certain-types-default-implementation-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!