haskell - If 语句使用 IO Int haskell

标签 haskell random functional-programming haskell-stack io-monad

我有一个游戏,用户对电脑,我想随机选择谁开始游戏。我有

a = getStdRandom $ randomR (0, 1)

这会得到一个随机数 0 或 1。但是它是一个 IO Int,所以我不能用 if 语句将它与类似的数字进行比较

if a == 0 then userStarts else computerStarts 

我试过比较 IO IntIO Int 但它不起作用,我也试过了

Converting IO Int to 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/

相关文章:

random - 为诅咒词清理随机字符串是否不合理?

python - 在python中获取随机 bool 值?

haskell - 直觉类型理论的组合逻辑等价物是什么?

java - 在 Scala 的案例类和类字段中使用 Optional 是否有代码味道?

function - 如何在 Rust 中实现多级柯里化(Currying)函数?

haskell - 使用具有约束类型的方法的类型类实例

excel - 在 Haskell 中从 Excel 读取数据

javascript - 是否可以用 Haskell 编写后端并用 Javascript 编写前端?

haskell - 使用带有堆栈的自定义 ghcjs fork

python - sklearn 随机状态不是随机的