在运行时检查类型是否为Show in Haskell的实例? [英] Check whether a type is an instance of Show in Haskell at runtime?

查看:20
本文介绍了在运行时检查类型是否为Show in Haskell的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在Haskell中有一个用于存储值的简单数据类型:

data V a = V a

我想使V成为Show的实例,而不考虑a的类型。如果a是Show的实例,则show (V a)应返回show a,否则应返回错误消息。或在伪哈斯克尔中:

instance Show (V a) where
    show (V a) = if a instanceof Show
                   then show a
                   else "Some Error."

如何在Haskell中实现此行为?

推荐答案

正如我在评论中所说,内存中分配的运行时对象在Haskell程序中没有类型标记。因此,没有像在Java中那样的通用instanceof操作。

考虑以下含义也很重要。在Haskell中,大体上来说(即忽略一些新手不应该过早使用撞击的花哨东西),所有运行时函数调用都是单态的。即,编译器直接或间接知道可执行程序中的每个函数调用的单态(非泛型)类型。即使您的V类型的show函数具有泛型类型:

-- Specialized to `V a`
show :: V a -> String  -- generic; has variable `a`
如果不直接或间接地告诉编译器每个调用中将是什么类型a,您就不能实际编写在运行时调用函数的程序。例如:

-- Here you tell it directly that `a := Int`
example1 = show (V (1 :: Int)) 

-- Here you're not saying which type `a` is, but this just "puts off" 
-- the decision—for `example2` to be called, *something* in the call
-- graph will have to pick a monomorphic type for `a`.
example2 :: a -> String
example2 x = show (V x) ++ example1

从这个角度看,希望您能发现问题所在:

instance Show (V a) where
    show (V a) = if a instanceof Show
                   then show a
                   else "Some Error."
基本上,由于a参数的类型对于您的show函数的任何实际调用在编译时都是已知的,因此在运行时测试此类型没有意义-您可以在编译时测试它!一旦你掌握了这一点,你就会看到威尔·休厄尔的建议:

-- No call to `show (V x)` will compile unless `x` is of a `Show` type.
instance Show a => Show (V a) where ...

edit:一个更有建设性的答案可能是:您的V类型需要是多个案例的标记联合。这确实需要使用GADTs扩展名:

{-# LANGUAGE GADTs #-}

-- This definition requires `GADTs`.  It has two constructors:
data V a where
  -- The `Showable` constructor can only be used with `Show` types.
  Showable   :: Show a => a -> V a
  -- The `Unshowable` constructor can be used with any type.
  Unshowable :: a -> V a

instance Show (V a) where
  show (Showable a) = show a
  show (Unshowable a) = "Some Error."

但这不是对类型是否为Show实例的运行时检查-您的代码负责在编译时知道要在何处使用Showable构造函数。

这篇关于在运行时检查类型是否为Show in Haskell的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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