在Haskell中从Int获取sqrt [英] Get sqrt from Int in Haskell

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

问题描述

如何从 Int 获取 sqrt



我这样做:

  sqrt。 fromInteger x 

但是获得类型兼容性的错误。

解决方案使用 fromIntegral

 前奏>让x = 5 :: Int 
Prelude> sqrt(fromIntegral x)
2.23606797749979

Int Integer Integral 的实例:




  • fromIntegral ::(Integral a,Num b)=> a - > b 将你的 Int (它是 Integral 的一个实例)并且制作它 Num


  • sqrt ::(Floating a)=> a - >一个需要一个浮动,并且浮动小数,它继承自 Num ,因此您可以安全地传递给 sqrt < c $ c> fromIntegral




我认为类 diagram Haskell Wikibook 在这种情况下非常有用。


How can I get sqrt from Int.

I try so:

sqrt . fromInteger x

But get error with types compatibility.

解决方案

Using fromIntegral:

Prelude> let x = 5::Int
Prelude> sqrt (fromIntegral  x)
2.23606797749979

both Int and Integer are instances of Integral:

  • fromIntegral :: (Integral a, Num b) => a -> b takes your Int (which is an instance of Integral) and "makes" it a Num.

  • sqrt :: (Floating a) => a -> a expects a Floating, and Floating inherit from Fractional, which inherits from Num, so you can safely pass to sqrt the result of fromIntegral

I think that the classes diagram in Haskell Wikibook is quite useful in this cases.

这篇关于在Haskell中从Int获取sqrt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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