[英]Type errors in haskell
从本教程开始的过去几个小时里,我确实开始学习haskell。 尝试编译以下代码时,我不断收到Couldn't match type
错误:
module Main where
import Control.Monad
main = do
putStrLn "Enter child age"
input <- getLine
-- convert the string to int
let age = read input :: Int
unless (age == 0) $ do
-- let ages = []
-- print age
-- add child age to list here?
ages ++ [age]
main
这是错误:
Couldn't match type `IO' with `[]'
Expected type: [()]
Actual type: IO ()
我已经搜索了几个小时,试图了解该问题,但是没有任何线索。 为什么ages ++ [age2]
期望使用IO Int
类型? 以及如何解决这个问题?
更新: ages
是一个列表,其中将包含两个孩子的年龄。 将来会使用。 还创建了循环
ages ++ [age1]
和ages ++ [age2]
是导致[Int]
表达式。 他们不会改变ages
; ages
只是一种价值。 由于您根本没有使用ages
,一个真正简单的解决方法是将所有三行都删除:
let ages = []
ages ++ [age1]
ages ++ [age2]
如果您打算将age1
和age2
用作[age1, age2]
则可以构建ages
。 如果您想使用列表不重复自己,那么您可能会在Haskell中按照以下方式进行更多操作:
readAge :: String -> IO Int
readAge prompt = do
putStrLn prompt
readLn :: IO Int
main = do
ages <- mapM readAge ["Enter child 1 age", "Enter child 2 age"]
print ages
要循环执行此操作,您可以从以下内容开始:
readAges :: IO [Int]
readAges = do
putStrLn "Enter child age"
age <- readLn :: IO Int
if age == 0 then
return []
else
fmap (age:) readAges
main :: IO ()
main = do
ages <- readAges
print ages
其中fmap (age:) readAges
的缩写:
ages <- readAges
return $ age : ages
在Haskell中,变量是不可变的。 您可能正在寻找更像这样的东西:
inputAges :: [Int] -> IO [Int]
inputAges (0:otherAges) = return otherAges
inputAges ages = _
此递归函数在其参数中跟踪年龄。 定义的第一行检查是否最近读取的年龄是0
。 如果是这样,它将给您除0
所有0
。 如果列表具有至少一个元素且其头为0
则它将与模式(0:otherAges)
匹配。 如果匹配,则将尾部绑定到otherAges
。 否则,它将转到下一个模式(此处为下一行)。
我没有填写递归案例,但是我可以在此方面提供更多帮助。 您需要一些可以读入年龄的东西,并以带有新年龄的列表进行调用。 部分阅读内容与问题代码中的内容大致相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.