0

我正在学习在 Haskell 中使用输入和输出。我正在尝试生成一个随机数并将其输出到另一个文件。问题是随机数似乎返回了一个IO Int我无法转换为Stringusing的东西show

有人可以在这里给我指点吗?

4

2 回答 2

10

如果您向我们展示您编写的不起作用的代码,这将很有帮助。

不管怎样,你在一个do街区里写了这样的东西,是吗?

main = do
    ...
    writeFile "some-file.txt" (show generateRandomNumberSomehow)
    ...

您应该改为执行以下操作:

main = do
    ...
    randomNumber <- generateRandomNumberSomehow
    writeFile "some-file.txt" (show randomNumber)
    ...

运算符将右侧值的结果绑定到左侧的-valued<-变量。(是的,您也可以使用它来将值的结果绑定到-valued 变量等)IO IntIntIO StringString

此语法仅在do块内有效。重要的是要注意,do块本身会产生一个 IO 值——你不能洗掉 IO-ness。

于 2012-10-15T09:38:19.817 回答
5

dave4420's answer is what you want here. It uses the fact that IO is a Monad; that's why you can use the do notation.

However, I think it's worth mentioning that the concept of "applying a function to a value that's not 'open', but inside some wrapper" is actually more general than IO and more general than monads. It's what we have the Functor class for.

For any functor f (this could, for instance, be Maybe or [] or IO), when you have some value
wrapped :: f t (for instance wrapped :: Maybe Int), you can use fmap to apply a function
t -> t' to it (like show :: Int -> String) and get a
wrappedApplied :: f t' (like wrappedApplied :: Maybe String).

In your example, it would be

genRandomNumAsString :: IO String
genRandomNumAsString = fmap show genRandomNumPlain
于 2012-10-15T10:48:33.113 回答