【问题标题】:Typeclass representing functions表示函数的类型类
【发布时间】:2013-12-21 01:40:27
【问题描述】:

如果这是一个愚蠢的问题,请原谅我,但是是否有代表所有功能的类型类?比如,假设我有这样的类型

data Foo a = Thing a 

instance (Show a) => Show (Foo a) where
    show (Thing a) = show a

我想显示Thing (\x -> 1)。也许对漂亮地打印一些关于此的元数据的方法进行某种反思?

试了会出现以下错误

> Thing (\x -> 1)

<interactive>:113:1:
    No instance for (Show (t0 -> a0)) arising from a use of `print'
    Possible fix: add an instance declaration for (Show (t0 -> a0))
    In a stmt of an interactive GHCi command: print it

<interactive>:113:14:
    No instance for (Num a0) arising from the literal `1'
    The type variable `a0' is ambiguous
    Possible fix: add a type signature that fixes these type variable(s)
    Note: there are several potential instances:
      instance Num Double -- Defined in `GHC.Float'
      instance Num Float -- Defined in `GHC.Float'
      instance Integral a => Num (GHC.Real.Ratio a)
        -- Defined in `GHC.Real'
      ...plus 11 others
    In the expression: 1
    In the first argument of `Thing', namely `(\ x -> 1)'
    In the expression: Thing (\ x -> 1)

这是有道理的,因为t0 -&gt; a0 没有show 的实例,但我不确定如何描述这个类型类的实例?

这不是为了任何制作,我只是在玩 Haskell,好奇我能做什么,不能做什么。

【问题讨论】:

  • 如果你想要一个占位符实例以便显示函数然后导入Text.Show.Functions
  • 酷,谢谢!我知道我错过了什么。
  • 函数不能是Show 的实例。看起来很容易,但是对于编译器来说,在编译、优化和组装之后很难获得信息。甚至可以在运行时创建新函数,所以这让事情变得相当复杂。您可能会使用模板 haskell 来管理它,该模板会生成像 data Func a = Func a String 这样的类型值,其中函数定义可以被推入字符串中,而函数本身则位于 a 插槽中。然后,您可以为其创建一个简单的 Show 实例。但这很难写。
  • 好的,谢谢。这是有道理的,我不确定这是否可能。感谢您的回答
  • 还有一个 answer 到其他地方,他们使用 Control.Category 向函数添加名称并使用 . 组合它们。或者,您可以使用Data.DatatypeOf 创建一个Show 实例,它只告诉您函数的类型,但这不适用于多态函数。

标签: haskell typeclass


【解决方案1】:

由于您的目标只是玩得开心,您可能会喜欢Data.Universe.Instances.Show。不过,对于更严肃的目标,您可能希望等到 Cloud Haskell 项目取得一些进展,该项目的部分目标是有一种方法来序列化和反序列化函数,以便它们可以跨机器迁移。

【讨论】:

  • 有什么魔法可以在我的电脑死机之前打印一个 Int64 -> Int64 吗?此外,我认为 OP(我也是)希望显示源代码,就像在 R 或 Scheme 中可以做的那样。有什么办法吗?云哈斯克尔? hackage.haskell.org/package/universe-0.4.0.4/docs/src/…
  • @misterbee 对,要能够序列化和反序列化代码,必须等待 Cloud Haskell。或者定义您自己的语言并将其嵌入。
  • 维基页面显示 Cloud Haskell 已发布并鼓励使用。此外,如果程序员愿意命名所有可能显示的“基本”函数和组合子(但不是所有函数),看起来静态标签可能会起作用hackage.haskell.org/package/distributed-static-0.2.1.1/docs/…
猜你喜欢
  • 1970-01-01
  • 2022-01-16
  • 2023-04-04
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
相关资源
最近更新 更多