Haskell 使用Data.Typeable';使用本地定义的数据类型强制转换

Haskell 使用Data.Typeable';使用本地定义的数据类型强制转换,haskell,types,casting,Haskell,Types,Casting,我有一个数据类型,我用它来表示wxHaskell中的对象,目前我只支持wxAnys,其中包含String或Int,因此: data Any = IsString String | IsInt Int | IsUndefined 我需要一个函数(a->Any),我想知道我是否可以使用数据优雅地完成它。可键入的,或者是否有人可以建议另一种方法?您可以相对简单地通过将cast函数与模式保护组合来完成: f :: Typeable a => a -> Any f x |

我有一个数据类型,我用它来表示wxHaskell中的对象,目前我只支持
wxAny
s,其中包含
String
Int
,因此:

data Any
  = IsString String
  | IsInt Int
  | IsUndefined

我需要一个函数(
a->Any
),我想知道我是否可以使用
数据优雅地完成它。可键入的
,或者是否有人可以建议另一种方法?

您可以相对简单地通过将
cast
函数与模式保护组合来完成:

f :: Typeable a => a -> Any
f x
    | Just s <- cast x = IsString s
    | Just n <- cast x = IsInt n
    | otherwise = IsUndefined
f::Typeable a=>a->Any
f x

|Just s您可以通过将
cast
功能与pattern guards相结合来实现:

f :: Typeable a => a -> Any
f x
    | Just s <- cast x = IsString s
    | Just n <- cast x = IsInt n
    | otherwise = IsUndefined
f::Typeable a=>a->Any
f x

|仅s您可以为此使用类型类:

class ToAny a where
  toAny :: a -> Any

instance ToAny Int where
  toAny = IsInt

instance ToAny String where
  toAny = IsString

对于另一种情况,您不能对其他类型的值调用该函数,这将减少代码量。

您可以使用类型类来实现这一点:

class ToAny a where
  toAny :: a -> Any

instance ToAny Int where
  toAny = IsInt

instance ToAny String where
  toAny = IsString

对于另一种情况,您不能对其他类型的值调用该函数,这将是更少的代码。

它如何知道s和n是不同的?它如何知道s和n是不同的?