如何为某些类型创建专用类型类,其余类型的默认实现(How to make specialized type classes for certain types, default implementat

编程入门 行业动态 更新时间:2024-10-13 00:30:48
如何为某些类型创建专用类型类,其余类型的默认实现(How to make specialized type classes for certain types, default implementation for the rest of types)

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

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

现在,该类将针对某些类型实现,对于所有其他类型,我希望具有默认实现。

怎么能这样做?

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?

最满意答案

它不一定是安全的或Haskell-y的事情,但它肯定是可能的,使用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

最后,所有类型的一般实例:

instance Castable a b where

使用示例:

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

运行此选项时,如果类型不是专用的,则选择默认值:

*Main> main Just True Nothing

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

更多推荐

本文发布于:2023-08-07 14:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464536.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   何为   type   specialized   classes

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!