我写了这段代码:
import GHC.Float
next :: GHC.Float -> GHC.Float-> GHC.Float
next n x = (x + n / x) / 2
我收到以下错误:
numerical.hs:3:9:
Not in scope: type constructor or class `GHC.Float'
numerical.hs:3:22:
Not in scope: type constructor or class `GHC.Float'
numerical.hs:3:34:
Not in scope: type constructor or class `GHC.Float'
模块导入没有任何问题,所以我不确定我是用错误的名称引用它还是标准Float模块与IEEE GHC.Float模块相同而且不需要显式导入它
我尝试执行import GHC.Float as Fl
但没有成功 - 在Fl
上遇到了相同的类型错误。
我刚刚开始Haskell(显然),所以任何帮助都会受到赞赏!
答案 0 :(得分:5)
您不必手动导入GHC.Float
,只需编写Float
,就像这样
next :: Float -> Float -> Float
next n x = (x + n / x) / 2
GHC在您拥有的每个源文件中隐式导入名为Prelude
的模块。 Prelude
包含许多方便的类型,函数和其他用作语言“内置函数”的东西。类似Int
,Float
,Maybe
,IO
以及head
,+
,/
等功能。
您可以使用isIEEE
模块中的函数GHC.Float
测试浮点数是否为IEEE浮点数:
import GHC.Float
main = do
putStr "1.0 is an IEEE floating point: "
print $ isIEEE (1.0 :: Float)
如果你运行它,它将打印True
我还应该提到你的代码之前没有编译的原因是因为当你导入一个只有import
的模块时,它的所有内容都进入了范围。您可以使用import qualified
强制它进行限定,以下是一些示例:
import GHC.Float -- Everything now in scope
import qualified Data.Maybe -- Have to use full name
import qualified Data.List as L -- aliased to L
main = do
-- Don't have to type GHC.Float.isIEEE
print $ isIEEE (1.0 :: Float)
-- Have to use full name
print $ Data.Maybe.isJust $ Nothing
-- Uses aliased name
print $ L.sort [1, 4, 2, 5, 3]