Haskell为什么要“Num x”需要“显示x”? [英] Haskell why does "Num x" require "Show x"?

查看:130
本文介绍了Haskell为什么要“Num x”需要“显示x”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我使用 LYAH 来看看Haskell。



  foo ::(Num x)=>这是一个快速测试函数。 x  - >字符串
foo x =显示x ++!

但是会产生这个错误:

<$ p $ b $ test.hs:2:9:
从上下文中使用`show'
引起的(显示x)(Num x)
由foo :: Num x =>的类型签名绑定。 x - >字符串
在test.hs:1:8-29
可能的修正:
添加(显示x)到
的上下文foo :: Num x =>的类型签名; x - >字符串

但是根据LYAH:


为了加入Num,一个类型必须已经是Show和Eq的朋友。

code> Num 是显示 Eq 的子集,为什么我需要将类型签名更改为 foo ::(Num x,Show x)=> x - >字符串为此工作?难道不可能推断出 Num 也是可显示的吗?

解决方案

div>

LYAH的信息很旧。 GHC 7.4.1发布说明说:


Num类不再有Eq或Show超类。


您需要编写

  foo ::(Num x,Show x)= > x  - >字符串

(事实上, foo 你写不需要 Num x ,所以你可以忽略它以避免不必要的约束。)


Recently I took a look at Haskell, using LYAH.

I was messing around with type classes and wrote this quick test function:

foo :: (Num x) => x -> String
foo x = show x ++ "!"

But that produces this error:

test.hs:2:9:
    Could not deduce (Show x) arising from a use of `show'
    from the context (Num x)
    bound by the type signature for foo :: Num x => x -> String
    at test.hs:1:8-29
    Possible fix:
      add (Show x) to the context of
        the type signature for foo :: Num x => x -> String

But according to LYAH:

To join Num, a type must already be friends with Show and Eq.

So if everything in Num is a subset of Show and Eq, why do I need to change the type signature to foo :: (Num x, Show x) => x -> String for this to work? Shouldn't it be possible to infer that a Num is also Show-able?

解决方案

The information in LYAH is old. The release notes for GHC 7.4.1 say that:

The Num class no longer has Eq or Show superclasses.

You will need to write,

foo :: (Num x, Show x) => x -> String

(In fact, the foo you wrote doesn't require Num x, so you can omit that to avoid an unnecessary constraint.)

这篇关于Haskell为什么要“Num x”需要“显示x”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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