我有一个游戏,用户对电脑,我想随机选择谁开始游戏。我有
a = getStdRandom $ randomR (0, 1)
这会得到一个随机数 0 或 1。但是它是一个 IO Int
,所以我不能用 if 语句将它与类似的数字进行比较
if a == 0 then userStarts else computerStarts
我试过比较 IO Int
和 IO Int
但它不起作用,我也试过了
我是 Haskell 的新手,不知道如何处理这个问题。请求的代码详细信息:
randomNumber = getStdRandom $ randomR (0, length symbols - 5) -- this will be 0 or 1
randomNumber2 = getStdRandom $ randomR (0, length symbols - 5) -- according to
-- the solution I need another function returning IO int.
a = do
x <- randomNumber
randomNumber2 $ pureFunction x
我得到的错误:
• Couldn't match expected type ‘t0 -> IO b
with actual type ‘IO Int’
• The first argument of ($) takes one argument,
but its type ‘IO Int’ has none
In a stmt of a 'do' block: randomNumber2 $ pureFunction x
In the expression:
do x <- randomNumber
randomNumber2 $ pureFunction x
• Relevant bindings include
a :: IO b
(bound at Path:87:1)
randomNumber2 $ pureFunction x
Path:89:20: error:
Variable not in scope: pureFunction :: Int -> t0
randomNumber2 $ pureFunction x
最佳答案
当你说 a = getStdRandom $ randomR (0,1)
你是说“让 a 成为获取 0 到 1 之间的随机值的 Action ”。你想要的是在某个函数的 do block 中 a <- getStdRandom $ randomR (0,1)
这是“让 a 成为运行获取 0 到 1 之间的随机值的操作的结果”。
因此:
import System.Random
main :: IO ()
main = do
a <- getStdRandom $ randomR (0, 1 :: Int)
if a == 0 then userStarts else computerStarts
-- Placeholders for completeness
userStarts, computerStarts :: IO ()
userStarts = putStrLn "user"
computerStarts = putStrLn "computer"
注意我指定了 1
是一个 int,否则编译器将不知道您是否想要一个随机 int、int64、double、float 或其他完全不同的东西。
编辑:@monocell 提出了一个很好的观点,即在一个范围内生成一个 int 只是为了获得一个 bool 值有点间接。您可以直接生成 bool 结果,这不需要范围:
a <- getStdRandom random
if a then userStarts else computerStarts
关于haskell - If 语句使用 IO Int haskell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54557803/