我不明白的GHC类型错误 [英] GHC type error which I do not understand

查看:62
本文介绍了我不明白的GHC类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在自学Haskell.

I am teaching myself Haskell.

我想编写一个函数来递归地找到第一个具有整数平方根且小于起始数字的数字.

I want to write a function that recursively finds the first number that has an integer square root and is smaller than a starting number.

它看起来像这样:

findFirstSquare :: Int -> Int
findFirstSquare x
    | x <= 0                                  = error "This function only works for 1 or above"
    | fromInteger(floor(sqrt(x))) == (sqrt x) = x
    | otherwise                               = intSqrt(x - 1)

但是GHC抱怨:

在...中没有使用(floor)引起的(RealFrac Int)实例.

No instance for (RealFrac Int) arising from a use of `floor' at ...

但是,如果我在GHCi中键入以下内容,它将很高兴地对其进行编译:

However, if I type the following into GHCi, it happily compiles it:

 fromInteger(floor(sqrt(4))) == (sqrt 4)

我的问题是:为什么我从在GHCi中成功编译的表达式中得到类型错误?

My question is: Why am I getting a type error from an expression that compiles successfully in GHCi?

推荐答案

好,我知道了.

区别在于常量"4"已重载,因此交互式sqrt(4)获得 Float 4

The difference is that the constant "4" is overloaded, so interactively sqrt(4) is getting the square root of the Float 4

但是我的函数将x声明为 Int ,因此我需要在sqrt调用中添加fromIntegral,以便它们能够正常工作.

However my function declares x as an Int, therefore I needed to add a fromIntegral to the calls to sqrt, so that they would work.

将中卫换成以下技巧:

| fromIntegral(floor(sqrt(fromIntegral(x)))) == (sqrt(fromIntegral(x))) = x

这篇关于我不明白的GHC类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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