Home > OS >  Haskell [IO Int] to [IO Char] output
Haskell [IO Int] to [IO Char] output

Time:08-12

With using randomRIO (0, 5 :: Int) I create a list of type [IO Int]. Let's say the list consists of 4 numbers (e.g. [3, 5, 2, 3]). I would then like to generate the output 3, 5, 2, 3 where it could also be the case that I may need to convert a number into a letter (hence they need to become chars). I have tried for some time now to do this but I haven't found any solution yet. How would I go about this?

CodePudding user response:

If you want to do something to the Int in [IO Int], you can first use sequence to turn it into IO [Int], then use do notation to manipulate the [Int] conveniently.

myFunc :: IO ()
myFunc = do
  randInts <- sequence (someFunctionThatCreatesListOfIOInt) -- here the type of randInts is [Int]
  let result = pureFunctionOnInts randInts
  print result

Thanks the comment that pointed out randomRIO (0, 5) produces IO Int instead a list of them. In this case, it is more convenient to work with it individually rather than having a list of IO actions.

Note that you (almost) cannot turn IO a into a because this breaks referential transparency. Of course, there are unsafe functions that do that, but it's ill-advised to use them unless you are absolutely sure on what are you doing.

Edit: to get the four random numbers, you can do the following:

myFunc = do
  randInts <- replicateM 4 (randomIO (0, 5 :: Int)) -- here are four random integers between 0 and 5
  let result = doSomethingToInts randInts
  print result

Of course, you can return the result instead of printing it so that it can be binded with other IO actions.

  • Related