以下(工作)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 ‘(<$>)’, …Run Code Online (Sandbox Code Playgroud) 为什么以下内容不能打印任何内容:
?> fmap print (pure 2)
Run Code Online (Sandbox Code Playgroud)
虽然这样的工作:
?> fmap id (pure 2)
2
Run Code Online (Sandbox Code Playgroud)