我正在尝试使用ghci将自定义模块导入到main中,但出现了我不太了解的错误。
Main.hs
module Main where
import Newton (my_sqrt)
main = my_sqrt 25
Newton.hs
module Newton where
deriv f x = (f(x + dx) - f(x))/dx
where dx = 0.0001
newton f = until satis improve
where satis y = abs(f y) < eps
eps = 0.0001
improve y = y - (f y/deriv f y)
my_sqrt x = newton f x
where f y = y^2 - x
my_cubrt x = newton f x
where f y = y**3 - x
我尝试使用将它们加载到ghci中
:l Main.hs
我收到此错误
Main.hs:9:8: error:
• No instance for (Fractional (IO t0))
arising from a use of ‘my_sqrt’
• In the expression: my_sqrt 25
In an equation for ‘main’: main = my_sqrt 25
Main.hs:9:16: error:
• No instance for (Num (IO t0)) arising from the literal ‘25’
• In the first argument of ‘my_sqrt’, namely ‘25’
In the expression: my_sqrt 25
In an equation for ‘main’: main = my_sqrt 25
Failed, modules loaded: Newton.
我该如何解决这个问题?
答案 0 :(得分:2)
main
的类型必须为IO ()
。
sqrt 25
的类型显然是Fractional t => t
(在程序中始终建议包含顶级实体的类型签名是很明智的;您会错过这些签名)。
要使两者协调一致,您可以定义例如
main :: IO ()
main = print (sqrt 25)
因为print
的类型为print :: Show a => a -> IO ()
。