如果使用IO诠释哈斯克尔声明

问题描述 投票:2回答:2

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

a = getStdRandom $ randomR (0, 1)

这得到一个随机数0或1。然而,它是一个IO Int,所以我不能有一个if语句相对于一个像数

if a == 0 then userStarts else computerStarts 

我曾尝试与IO Int比较IO Int,它不工作,我也试着

Converting IO Int to Int

我是很新的哈斯克尔,不知道如何处理这一点。代码的细节要求:

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
haskell random functional-programming haskell-stack io-monad
2个回答
12
投票

当你说你说a = getStdRandom $ randomR (0,1)“让得到好0和1之间的随机值的作用”。你需要的是一些功能我们做块a <- getStdRandom $ randomR (0,1)这是“让正在运行得到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的,双,浮法,或别的东西完全。

编辑:@monocell使得一个好点,在一个范围内产生一个int只是为了得到一个布尔有点间接的。您可以只需直接生成布尔结果,这不需要范围:

  a <- getStdRandom random
  if a then userStarts else computerStarts

3
投票

不知道如何代码的样子,但你有没有试图做链接的资源推荐什么(使用DO块)?

do
   (result, newGenerator) <- randomR (0, 1) generator
   -- ...

这将让你获得result,这是同类型01的。

你能告诉你的代码/你的错误?

© www.soinside.com 2019 - 2024. All rights reserved.