关于Haskell中数据类型的混乱
我必须写一个简单的pi近似值,我做到了,而且效果很好,但是在任务中,它说要用标题“ pi_approx :: int - > double”编写功能。
我的代码:
pi_approx x = sqrt (pi2_approx(x))
pi2_approx x =
if x/= 1
then (6 /(x*x)) + (pi2_approx(x-1))
else (6/(1*1))
但是,我的功能在没有“ pi_approx :: int - > double”的情况下正常工作,但是当我尝试使用此声明时,我总是会收到类型错误:
pi_approx.hs:10:14:错误:错误:
- 无法匹配预期的预期类型
double'带有实际类型< / code> int'
- 在表达式中:(+)(6 /(x * x))(pi2_approx(x -1)) 在表达中: 如果x /= 1,则 (+)(6 /(x * x))(pi2_approx(x -1)) 别的 (6 /(1 * 1)) 在“ pi2_approx”的方程式中: pi2_approx x =如果x /= 1,然后 (+)(6 /(x * x))(pi2_approx(x -1)) 别的 (6 /(1 * 1)) | 10 |然后(+)(6 /(x*x))(pi2_approx(x-1)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^es
》以各种方式使用从集合的方式,如果我在没有声明的情况下运行函数,我会检查解决方案的类型,即:“(浮动a,eq a)=&gt; a”,
因为我理解double应该是浮动的一个实例,所以我不明白为什么它不会编译。
我在哈斯克尔(Haskell)很新,看来我不了解数据类型和约束的核心概念。不过,我似乎无法找到有关该主题的任何简单良好的文档/解释。也许这里有人可以根据这个示例帮助我理解:)
I have to write a simple pi approximation and I did and it works fine, but in the task it says to write a function with the header "pi_approx :: Int -> Double".
My code:
pi_approx x = sqrt (pi2_approx(x))
pi2_approx x =
if x/= 1
then (6 /(x*x)) + (pi2_approx(x-1))
else (6/(1*1))
However my function works fine without "pi_approx :: Int -> Double", but when i try to use this declaration I always get the type error:
pi_approx.hs:10:14: error:
- Couldn't match expected type
Double' with actual type
Int' - In the expression: (+) (6 / (x * x)) (pi2_approx (x - 1))
In the expression:
if x /= 1 then
(+) (6 / (x * x)) (pi2_approx (x - 1))
else
(6 / (1 * 1))
In an equation for `pi2_approx':
pi2_approx x
= if x /= 1 then
(+) (6 / (x * x)) (pi2_approx (x - 1))
else
(6 / (1 * 1))
|
10 | then (+) (6 /(x*x)) (pi2_approx(x-1))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
I tried to use fromIntegral in various ways and if I run the function without declaration I checked the type of the solution, which is: "(Floating a, Eq a) => a"
As I understand Double should be an instance of Floating so I don´t understand why it wont compile.
I am very new at haskell and it seems I don´t understand the core concept of data types and constraints. I can´t seem to find any simple and good documentation/explanation on the topic though. Maybe someone here can help me understand based on this example :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为
x
是int
,因此x * x
也是int
,您无法使用<代码> int(/):: floating a =&gt; a - &gt; a - &gt;
。您需要将其转换为
double
,例如使用fromIntegral ::(Integral a,num b)=&gt; a - &gt; B
:对于大量迭代,它给出了接近π 2 的结果。
because
x
is anInt
, hencex * x
is also anInt
, and you can not use anInt
for(/) :: Floating a => a -> a -> a
.You need to convert this to a
Double
, for example withfromIntegral :: (Integral a, Num b) => a -> b
:For a large number of iterations, it gives a result close to π2: