【发布时间】:2013-03-06 22:04:41
【问题描述】:
我正在尝试编写一个程序,让用户不断输入数字并在输入负数后输出平均值
这是我保留pure separate from unpure 的尝试
有人可以给我修复此代码的提示,以及纯和不纯的分离提示。
getFloat :: IO Float
getFloat = do line <- getLine
return (read line:: Float)
“不纯的部分”
average :: IO Float
average = do x <- getFloat
return((fst help x)/(snd help x))
“纯部分”
help x
|x>=0 = (x+sum1, 1+ counter)
|otherwise = (sum1 , counter)
where
sum1 = 0.0
counter = 0.0
我收到此错误
.hs:45:26:
Couldn't match expected type `(t0 -> Float, b0)'
with actual type `t1 -> (t1, t2)'
In the first argument of `fst', namely `help'
In the first argument of `(/)', namely `(fst help x)'
In the first argument of `return', namely
`((fst help x) / (snd help x))'
Failed, modules loaded: none.
【问题讨论】:
-
看起来更适合CodeReview。
-
这是一个愚蠢的方式告诉你
help不是一个元组,所以应用程序fst help是错误的。 -
我建议初学者编写更小的表达式,这样错误消息就不会那么混乱了。沿着
let a = ..; let b = ...; return $ a / b的行(替换;换行) -
@Ingo:除非您还在那里添加类型签名,否则不会有太大帮助
标签: haskell io functional-programming