我想问问题.我是Hakskell的biginner,我有一些非常简单的程序困难,应该告诉我divident%divider == 0.
我有这个代码:
f::Integer -> Integer -> Bool
f x y = if ((x `mod` y) == 0) then True
else False
main = do putStrLn "Set up dividend"
x <- getLine
putStrLn "Set Up divider"
y <- getLine
f read x::Int read y::Int
Run Code Online (Sandbox Code Playgroud)
但是当我想运行它时,我遇到了一个错误:
Couldn't match expected type `Int' with actual type `m0 b0'
Expected type: m0 a0 -> m0 b0 -> Int
Actual type: m0 a0 -> m0 b0 -> m0 b0
In a stmt of a 'do' block: putStrLn "Set up dividend"
In the expression:
do { putStrLn "Set up dividend";
x <- getLine;
putStrLn "Set Up divider";
y <- getLine;
.... } ::
Int
Run Code Online (Sandbox Code Playgroud)
我真的不知道,有什么不对.我也试过f x y (not f read x::Int .....)
没有任何结果.我必须做错事.我知道有很多关于这个问题的话题,但没有任何帮助.我错过了什么.
问题出在最后一行:
f read x::Int read y::Int
Run Code Online (Sandbox Code Playgroud)
这个代码基本上是说f read x read y
,类型Int
和f read x
类型也在哪里Int
.您必须添加括号,以便f
正确应用,并在正确的术语上使用类型注释.你得到:
f ((read x) :: Int) ((read y) :: Int)
-- or with fewer parentheses, but meaning the same thing:
f (read x :: Int) (read y :: Int)
Run Code Online (Sandbox Code Playgroud)
你的定义中的if语句f
也是不必要的,为什么不使用:
f x y = (x `mod` y) == 0
Run Code Online (Sandbox Code Playgroud)
f read x::Int read y::Int
Run Code Online (Sandbox Code Playgroud)
该应用功能f
的参数read
,x
,read
和y
.它也说f read y
应该是一个Int
结果,整个事情的结果也应该是一个Int
.那显然不是你想要的.你需要的是应用f
到的结果read x
和read y
,所以你需要围绕这些括号.
另一个问题是f
将Integer
s作为参数,但是你要告诉read
你Int
.您可以通过更改Int
为修复它,Integer
或者您可以完全删除类型注释,因为它们可以被推断.您还可以更改f
接受任何类型的类型Integral
,以便它可以同时使用Int
和Integer
.
Lastly the type of main
needs to be IO ()
, but your definition evaluates to a Bool
. Maybe you want to print the Bool
?
The combination of getLine
and read
can be simplified to readLine
by the way.
So you could do:
main = do putStrLn "Set up dividend"
x <- readLine
putStrLn "Set Up divider"
y <- readLine
print $ f x y
Run Code Online (Sandbox Code Playgroud)