在Haskell中将输出整数输出到stdout

Iul*_*urt 12 io haskell

我有一个简单的功能,如:

nth :: Integer -> Integer
Run Code Online (Sandbox Code Playgroud)

我尝试打印它的结果如下:

main = do
    n <- getLine
    result <- nth (read n :: Integer)
    print result
Run Code Online (Sandbox Code Playgroud)

生成以下错误:

Couldn't match expected type `IO t0' with actual type `Integer'
In the return type of a call of `nth'
In a stmt of a 'do' expression:
    result <- nth (read n :: Integer)
Run Code Online (Sandbox Code Playgroud)

也试过putStrLn和很多其他组合没有运气.
我无法理解,我需要一些帮助,因为我不完全理解这些东西是如何运作IO的.

Tho*_*son 14

nth是一个功能,而不是一个IO动作:

main = do
  n <- getLine
  let result = nth (read n :: Integer)
  print result
Run Code Online (Sandbox Code Playgroud)

  • 语法和绑定(`x < - action`)仅用于Monads.如果你是初学者,那么你使用的唯一monad就是`IO`.如果你的函数不是`func :: a - > IO b`形式,甚至只是`func :: IO b`,那么你不能使用bind但你可以使用let语句. (2认同)
  • 没有区别。`print(nth(read n :: Integer))`也可以工作。“ &lt;-”不是保存中间值,而是解包单子值。使用`let`保存中间值(在`do`块中,`let`与do块之外的语法略有不同),并使用&lt;&lt;-从单子值中提取值。 (2认同)

rot*_*off 5

do语法在monad中解开某些东西。箭头右手边的所有内容都必须位于IO monad内,否则类型不会检查。一个IO Integer是在你的程序的罚款。do是用于更明确功能的语法糖,其编写方式如下:

回顾 (>>=) :: m a -> (a -> m b) -> m b

main = getLine >>= (\x ->
       nth >>= (\y ->
       print y))
Run Code Online (Sandbox Code Playgroud)

但是nth不是一元值,因此应用该函数没有意义(>>=),因为该函数需要type IO a