如何加入两个 Haskell IO monad

hed*_*gie 3 random monads haskell io-monad

以下(工作)Haskell 程序输出随机拼写:

import System.Random

spells =
  [ "Abracadabra!"
  , "Hocus pocus!"
  , "Simsalabim!"
  ]

main :: IO()
main = do
  spell <- (spells !!) <$> randomRIO (0, length spells - 1)
  putStrLn spell
Run Code Online (Sandbox Code Playgroud)

然而,这个变量spell是非常无用的。它存储从法术列表中选择的随机字符串,但随后会立即传递给putStrLn函数并且不再使用。我尝试将两个 IO 操作合并为一行,如下所示:

main = putStrLn <$> (spells !!) <$> randomRIO (0, length spells - 1)
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

    • Couldn't match type ‘IO ()’ with ‘()’
      Expected type: Int -> ()
        Actual type: Int -> IO ()
    • In the first argument of ‘(<$>)’, namely
        ‘putStrLn <$> (spells !!)’
      In the expression:
        putStrLn <$> (spells !!) <$> randomRIO (0, length spells - 1)
      In an equation for ‘main’:
          main
            = putStrLn <$> (spells !!) <$> randomRIO (0, length spells - 1)
    |
160 | main = putStrLn <$> (spells !!) <$> randomRIO (0, length spells - 1)
    |        ^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

有没有办法将两个 IO 操作合并为一行?我看了这个类似的问题,但我无法理解答案。

ama*_*loy 7

(>>=)是 Robin Zigmond 的回答中给出的“规范”单子运算符。但是,如果您尝试以类似 applicative 的风格编写代码,我经常喜欢使用它的翻转版本(=<<). 它与 Functor 和 Applicative 中的函数具有很好的对称性,以及它们如何类似于普通的非 monadic 函数调用,只是插入了一个额外的运算符:

f x -- one-argument function call
f <$> fx -- fmapping that function into a functor
g x y -- two-argument function call
g <$> ax <*> ay -- applied over two applicatives
f =<< mx -- binding a function with a monadic value
mx >>= f -- looks backwards, doesn't it?
Run Code Online (Sandbox Code Playgroud)

所以你的表达可以写成

main = putStrLn =<< (spells !!) <$> randomRIO (0, length spells - 1)
Run Code Online (Sandbox Code Playgroud)

就我个人而言,我更愿意使用更普通的函数组合和更少的上下文映射,因此我将 移动(spells !!)到绑定运算符的左侧:

main = putStrLn . (spells !!) =<< randomRIO (0, length spells - 1)
Run Code Online (Sandbox Code Playgroud)

看看它是如何以这种方式很好地阅读的?“打印出”给出的索引处的拼写randomRIO (0, length spells - 1)


Rob*_*ond 6

do符号只是使用绑定运算符 ( >>=) 的语法糖。所以你的 2 行do块可以被重写:

main = do
    spells <- (spells !!) <$> randomRIO (0, length spells - 1)
    putStrLn spells

-- rewrite to bind notation

main = ((spells !!) <$> randomRIO (0, length spells - 1)) >>= \spells ->
    putStrLn spells

-- simplify the lambda

main = ((spells !!) <$> randomRIO (0, length spells - 1)) >>= putStrLn 
Run Code Online (Sandbox Code Playgroud)

但是,我会质疑在这里这样做是否有任何可读性或其他好处。