为什么这需要一个明确的类型? [英] Why does this need an explicit type?

查看:79
本文介绍了为什么这需要一个明确的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  { - #LANGUAGE FlexibleInstances# - }我在Haskell中使用类编写了一个泛型类型转换器。 

类可转换a其中
convert :: a

实例Convertable(Int - > String)其中
convert = show

实例Convertable(String - > Int)其中
convert = read

main = do
let result =((+1)。convert :: String - > ; Int)1
print result

但我需要显式类型字符串 - > Int 为了得到它的工作(哪种类型否定了泛型类型转换器的目的...)



为什么会这种类型的声明是完全需要的,只有一种可能性满足类型? 解决方案

转换不是这里的问题,默认情况下数字的类型是Num a => a,所以这里的问题是你在那里的+1。你必须给它一个具体的类型。


I wrote a generic type to type converter in Haskell using classes as follows:

{-# LANGUAGE FlexibleInstances #-}

class Convertable a where
    convert::a

instance Convertable (Int -> String) where
    convert = show

instance Convertable (String -> Int) where
    convert = read

main = do
    let result = ((+1) . convert :: String -> Int) "1"
    print result

But I need the explicit type String -> Int in order to get it to work (which kind of negates the purpose of having a generic type converter....)

Why would this type declaration be needed at all, there is just one possibility that satisfies the types?

解决方案

convert is not the problem here, numbers by default are of type Num a => a, so the problem here is +1 you have there. You have to give it a concrete type.

这篇关于为什么这需要一个明确的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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