如何为某些类型创建专门的类型类,其余类型的默认实现 [英] How to make specialized type classes for certain types, default implementation for the rest of types

查看:56
本文介绍了如何为某些类型创建专门的类型类,其余类型的默认实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有一个类型的类型类,可以在可能的情况下将其转换为其他类型.

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  

现在,该类将为某些类型实现,而 all 则为其他类型,我希望使用默认实现.

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

该怎么做?

推荐答案

这不一定是安全或Haskell-y要做的事情,但使用

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

首先,启用它们:

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

写您的演员表:

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

优化"实例:

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

示例用法:

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

这篇关于如何为某些类型创建专门的类型类,其余类型的默认实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆