类型代表函数 [英] Typeclass representing functions

查看:96
本文介绍了类型代表函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这是一个愚蠢的问题,请原谅我,但是有没有代表所有函数的类型类?喜欢,让我说我有这样的类型

  data Foo a = Thing a 

instance显示a)=> Show(Foo a)
show(Thing a)= show a

我想显示 Thing(\ x - > 1)。也许做一些反思的方法来打印一些关于这个元数据?

尝试它我得到以下错误

 > Thing(\ x  - > 1)

< interactive>:113:1:
由于使用`打印'
可能的修正:为(显示(t0 - > a0))添加一个实例声明
在一个交互式GHCi命令的列表中:打印它

< interactive> ;:113:14:
没有实例(数字a0)从文字'1'产生
类型变量'a0'不明确
可能的修正:添加修复这些的类型签名类型变量
注意:有几个潜在的实例:
实例Num Double - 在`GHC.Float'中定义
实例Num Float - 在`GHC.Float'中定义
实例Integral a => Num(GHC.Real.Ratio a)
- 在`GHC.Real'中定义
...加上另外11个
在表达式中:1
在第一个参数'Thing',即`(\ x - > 1)'
在表达式中:Thing(\ x - > 1)

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



这不适用于任何产品,我只是搞乱了Haskell,并且好奇我能做什么,不能做什么。

解决方案

既然你的目标只是为了获得乐趣,你可能会喜欢 Data.Universe.Instances.Show 。然而,对于更严肃的目标,您可能需要等到Cloud Haskell项目取得了一些进展,该项目部分目标是要有一种序列化和反序列化函数的方法,以便它们可以跨机器迁移。


Forgive me if this is a dumb question, but is there a typeclass that represents all functions? Like, lets say I have a type like this

data Foo a = Thing a 

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

And I want to display Thing (\x -> 1). Maybe do some sort o reflection on the method to pretty print some metadata about this?

Trying it I get the following error

> 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)

Which makes sense, since there is no instance of show for t0 -> a0 but I am not sure how to describe an instance of this typeclass?

This isn't for anything production, I am just messing around with Haskell and curious what I can and can't do.

解决方案

Since your goal is just to have fun, you might like Data.Universe.Instances.Show. For a more serious goal, though, you may want to wait until there's been some progress on the Cloud Haskell project, which aims in part to have a way to serialize and deserialize functions so that they can be migrated across machines.

这篇关于类型代表函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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