Haskell 求完美平方——出现类型错误

标签 haskell types casting functional-programming

我刚刚开始学习haskell,我尝试实现一个简单的函数来检查一个数字是否是平方根。我认为我在理解 Haskell 类型系统方面遇到了一些问题——我唯一的其他编程经验是 ruby​​ 和一些 Java。这就是我到目前为止所拥有的(抱歉,如果它真的很愚蠢):

isPerfectSquare :: (RealFloat t) => t -> Bool
isPerfectSquare n = 
    (sqrt n) == (truncate (sqrt n))

这就是我在 ruby​​ 中要做的...但是这里它给了我这个错误:

Could not deduce (Integral t) arising from a use of `truncate'
from the context (RealFloat t)
  bound by the type signature for
             isPerfectSquare :: RealFloat t => t -> Bool
  at more.hs:(73,1)-(74,35)
Possible fix:
  add (Integral t) to the context of
    the type signature for isPerfectSquare :: RealFloat t => t -> Bool
In the second argument of `(==)', namely `(truncate (sqrt n))'
In the expression: (sqrt n) == (truncate (sqrt n))
In an equation for `isPerfectSquare':
    isPerfectSquare n = (sqrt n) == (truncate (sqrt n))
Failed, modules loaded: none.

您能否解释一下问题是什么、如何解决它,以及最好是我不理解的任何基本概念?提前致谢。

最佳答案

sqrt 的类型为:

sqrt :: Floating a => a -> a

截断具有类型:

truncate :: (RealFrac a, Integral b) => a -> b

换句话说,sqrt 返回 float ,而 truncate 返回整数。您必须插入显式转换。在这种情况下,您可能需要 fromIntegral,它可以将任何整数类型转换为任何数字类型:

fromIntegral :: (Num b, Integral a) => a -> b

然后您可以进行比较:

(sqrt n) == (fromIntegral $ truncate (sqrt n))

关于Haskell 求完美平方——出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8611476/

相关文章:

c++ - 使用共享指针在两个类型模板化类之间进行转换

C++ 覆盖运算符 const char*

haskell - seq 函数和严格性

java - 如何修改 void 类方法使其返回所需信息

haskell - 一个棘手的haskell问题

oracle - Rails 5 - created_at 和 updated_at 类

c# - 从 CLR 样式的类型全名获取 C# 样式的类型引用

c++ - 如何将 32 位有符号整数值转换为 C 中等效的 64 位有符号整数

Haskell Cabal QuickCheck 集成

haskell - 将 <q> 和 </q> 标签更改为“特定位置的配对”