没有来自文字“5”的(Num(Int - > Int))实例, [英] No instance for (Num (Int -> Int)) arising from the literal `5'

查看:86
本文介绍了没有来自文字“5”的(Num(Int - > Int))实例,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能:

  f ::(Int  - > Int) - > Int 
f = undefined

现在我想调用 f < code $> $ 5 (这是不正确的):

  f 5 

显然,这不应该编译,因为 5 不是从 Int Int 的函数。
所以我希望有一个错误消息像无法匹配预期的类型Int - > Int with Int



但是我得到:

 没有为字面值'5'引起的(Num(Int  - > Int))实例
在'f'的第一个参数中,即'5'
在表达式中: f 5
在'it'的等式中:it = f 5

为什么 Num 出现在这里?

解决方案

code>是类 Num 中的任何类型。这些类型包括 Int Double 整数等。



函数不在class Num 默认类型中。然而,功能的 Num 实例可以由用户添加,例如,以逐点方式定义两个函数的总和。在这种情况下,文字 5 可以代表常数五的功能。



从技术上讲, fromInteger 5 ,其中 5 整数常量。因此,调用 f 5 实际上是 f(fromInteger 5),它试图将五个转换为 Int - > INT 。这需要一个 Num(Int - > Int)



的实例。因此,GHC没有声明错误: 5 不能是一个函数(因为它可能是,如果用户声明了它,提供一个合适的 fromInteger )。它只是说明,没有 Num 实例可以找到整数函数。


I have the following function:

f :: (Int -> Int) -> Int
f = undefined

Now I want to call f with 5 (which is incorrect):

f 5

Obviously, this should not compile, because 5 is not a function from Int to Int. So I would expect an error message like Couldn't match expected type Int -> Int with Int.

But instead I get:

No instance for (Num (Int -> Int)) arising from the literal `5'
In the first argument of `f', namely `5'
In the expression: f 5
In an equation for `it': it = f 5

Why did Num appear here?

解决方案

5 is of any type in type class Num. These types include Int, Double, Integer, etc.

Functions are not in type class Num by default. Yet, a Num instance for functions might be added by the user, e.g. defining the sum of two functions in a pointwise fashion. In such case, the literal 5 can stand for the constant-five function.

Techncally, the literal stands for fromInteger 5, where the 5 is an Integer constant. The call f 5 is therefore actually f (fromInteger 5), which tries to convert five into Int -> Int. This requires an instance of Num (Int -> Int).

Hence, GHC does not state in its error that 5 can not be a function (since it could be, if the user declared it such, providing a suitable fromInteger). It just states, correctly, that no Num instance can be found for integer functions.

这篇关于没有来自文字“5”的(Num(Int - > Int))实例,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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