Haskell sqrt类型错误 [英] Haskell sqrt type error

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

问题描述

好的,所以我试图编写一个Haskell函数,该函数可以有效地检测给定 Int 的所有因素.基于

OK, so I'm attempting to write a Haskell function which efficiently detects all the factors of a given Int. Based off of the solution given in this question, I've got the following:

-- returns a list of the factors of n
factors         ::  Int -> [Int]
factors n       =   sort . nub $ fs where
                        fs  =   foldr (++) [] [[m,n `div` m] | m <- [1..lim+1], n `mod` m == 0]
                        lim =   sqrt . fromIntegral $ n

不幸的是,GHCi通知我在包含 lim = 等的行中没有(浮点整数)的实例.

Sadly, GHCi informs me that there is No instance for (Floating Int) in the line containing lim = etc. etc.

我已经阅读了此答案,并且建议的解决方案在直接键入GHCi时有效-它允许我打电话 Int 上的 sqrt .但是,当在我的函数中放置看起来完全相同的代码时,它将停止工作.

I've read this answer, and the proposed solution works when typed into GHCi directly - it allows me to call sqrt on an Int. However, when what appears to be exactly the same code is placed in my function, it ceases to work.

我是Haskell的新手,所以非常感谢您的帮助!

I'm relatively new to Haskell, so I'd greatly appreciate the help!

推荐答案

当您检查 sqrt

Prelude> :t sqrt 
sqrt :: Floating a => a -> a

它需要一个浮点数.它在ghci中不起作用.您可能尝试过用数字调用它,而ghci会将类型推断为Float.

It requires a floating number. It doesn't work in ghci. You might have tried calling it on a number and ghci would have inferred the type as Float.

Prelude> let a = 1 :: Int

Prelude> sqrt a

<interactive>:5:1:
    No instance for (Floating Int) arising from a use of `sqrt'
    Possible fix: add an instance declaration for (Floating Int)
    In the expression: sqrt a
    In an equation for `it': it = sqrt a

现在返回您的代码.问题在于表达式 [1 .. lim + 1] .算术序列只能应用于 Enum a =>类型的值.一个.由于 lim 的类型为 Floating a =>a ,则需要将其转换回 Integral a =>a ,方法是采用天花板地板.仅作为参考, Integral 类实例也将类型约束为也具有 Enum 实例.

Now coming back to your code. The problem is in the expression [1 .. lim + 1]. Arithmetic sequences can only be applied on values of type Enum a => a. Since lim is of type Floating a => a, you need to convert it back to Integral a => a by either taking the ceiling or floor. Just for information, Integral class instance constraints the type to have an Enum instance too.

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

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