如何将IO int转换为Haskell中的字符串? [英] How to convert IO int to String in Haskell?
问题描述
如果您向我们展示您写的代码不是工作。
无论如何,你在一个 do
块并且写了类似的东西,是吗?
main = do
...
writeFilesome-file.txt(show generateRandomNumberSomehow)
...
您应该这样做:
pre code $ main $
randomNumber< - generateRandomNumberSomehow
writeFilesome-file.txt(show randomNumber)
...
< -
运算符将右边的 IO Int
值的结果绑定到左边的 Int
-valued变量。 (是的,您也可以使用它将 IO字符串
值的结果绑定到 String
-valued变量,等等)
这个语法只在 do
块内有效。请注意, do
块本身会产生一个IO值 - 您无法清除IO内存。
I'm learning to use input and output in Haskell. I'm trying to generate a random number and output it to another file. The problem is that the random number seems to be returning "IO int" that I can't covert it to String using "show". Could someone give me a pointer here??
It's helpful if you show us the code you've written that isn't working.
Anyway, you are in a do
block and have written something like this, yes?
main = do
...
writeFile "some-file.txt" (show generateRandomNumberSomehow)
...
You should instead do something like this:
main = do
...
randomNumber <- generateRandomNumberSomehow
writeFile "some-file.txt" (show randomNumber)
...
The <-
operator binds the result of the IO Int
value on the right to the Int
-valued variable on the left. (Yes, you can also use this to bind the result of an IO String
value to a String
-valued variable, etc.)
This syntax is only valid inside a do
block. It's important to note that the do
block will itself result in an IO value --- you can't launder away the IO-ness.
这篇关于如何将IO int转换为Haskell中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!