我的sqrt函数无法在GHCi中编译 [英] my sqrt function will not compile in GHCi

查看:41
本文介绍了我的sqrt函数无法在GHCi中编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个 Int 的平方根,Prelude sqrt 函数用于 Float⟶Float ,我需要 Int⟶浮动.

I want to get the squareroot of an Int, the Prelude sqrt function is for Float ⟶ Float and I need Int ⟶ Float.

尝试滚动自己的简单sqrt,我定义了两种类型,并从Hackage的Prelude源代码中复制了该函数: sqrt x = x ** 0.5

Attempting to roll my own simple sqrt I defined the two types and copied the function from the Prelude source code on Hackage: sqrt x = x ** 0.5

如此:

sqrt' :: Int -> Float
sqrt' x = x ** 0.5

给出错误:

    • Couldn't match expected type ‘Float’ with actual type ‘Int’
    • In the expression: x ** 0.5
      In an equation for ‘sqrt'’: sqrt' x = x ** 0.5
   |
19 | sqrt' x = x ** 0.5 
   |           ^^^^^^^^

我尝试使用中间变量和where子句等尝试不同的类型类定义,但没有任何乐趣.

I've tried different type class definitions, using an intermediary variable and the where clause and so on but no joy.

推荐答案

The (**) :: Floating a => a -> a -> a can only be applied to Floating types, and furthermore requires that both operands and the result all have the same type.

您的类型签名则表示 x Int ( Int not Floating 类型类的成员),并且 x ** 0.5 应该返回 Float ,因此这违反了的类型签名.(**).

Your type signature on the other hand, says that x is an Int (an Int is not a member of the Floating typeclass), and furthermore x ** 0.5 should return a Float, so this violates the type signature of (**).

我们可以转换

We can convert any type that is a member of the Integral typeclass to any type that is a member of the Num typeclass with fromIntegral :: (Integral a, Num b) => a -> b . In this case fromIntegral will thus convert an Int to a Float:

sqrt' :: Int -> Float
sqrt' x = fromIntegral x ** 0.5

这篇关于我的sqrt函数无法在GHCi中编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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