我正在尝试从命令行获取一个 int 值并将其传递给 disp
功能。
import System(getArgs)
main = do
args <- getArgs
disp $ read $ head args :: Int
disp n = take n $ repeat 'S'
ghc 给出的错误是
Couldn't match expected type `Int' with actual type `[Char]'
In the expression: disp $ read $ head args :: Int
In the expression:
do { args <- getArgs;
disp $ read $ head args :: Int }
In an equation for `main':
main
= do { args <- getArgs;
disp $ read $ head args :: Int }
谢谢。
最佳答案
问题在于优先级:类型签名总是尝试应用于整个表达式(仅使用括号限定范围)。所以你的disp $ read $ head args :: Int
解析为 (disp $ read $ head args) :: Int
,这显然是不正确的。您可以像这样使用括号:
disp (read $ head args :: Int)
或者省略类型签名,因为 GHC 在这种情况下可以推断它:
disp $ read $ head args
这段代码仍然不能按原样工作,因为你在 IO monad 中,所以你需要产生 IO Action 。您可以通过打印结果来做到这一点,例如:
putStrLn $ disp $ read $ head args
关于Haskell:如何在命令行中将 args 读取为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17993074/