English 中文(简体)
在Haskell随机显示的体格算时出现的问题
原标题:Problem when displaying integer arithmetic with a random number in Haskell

我要说的是,我要在Haskell产生随机数目。 为此,我不得不利用这段话。

randomRIO (0, 10)

这给我带来了0至10倍。 类型

randomRIO (0,10) :: (Random a, Num a) => IO a

Now, let s say I assign its result to a value k. It s type is IO Integer.

如<代码>k + 2,照常做计算,将产生以下结果:

<interactive>:1:3:
    No instance for (Num (IO Integer))
      arising from the literal `2 
    Possible fix: add an instance declaration for (Num (IO Integer))
    In the second argument of `(+) , namely `2 
    In the expression: k + 2
    In an equation for `it : it = k + 2

在试图询问Ghci时,问题也发生。

[randomRIO (0, 10) | x <- [0..10]]

错误信息是轨加密,我如何利用Haskell的随机数字?

最佳回答

<代码>IO Integer 的数值不是一种分类。 这一行动一旦实施,将重新分类。 区分是重要的。 执行<代码>IO行动的唯一途径是将其打上main/code>,或将其打入GHCi。

http://code>randomRIO (0, 10)。 请注意,这一职能是而不是,因为考虑到同样的投入,这一职能必须永远恢复相同的结果,尽管我们有时称之为impure function

因此,问题是,你如何采取行动,恢复愤怒,并采取行动,恢复愤怒加二者? 简便可使用<代码>fmap,将行动与将其结果转化为新行动的纯功能结合起来。

fmap (+2) $ randomRIO (0, 10)

<代码>Control. Monad载有从其他行动中开展新行动的许多有用职能。 就您的第二个例子而言,我们可以使用replicateM,从而形成一种行动,在采取这些行动时,可以多次采取最初的行动,将结果汇编成一个清单:

replicateM 10 $ randomRIO (0, 10)

也可通过人工方式使用<代码>do-notation获得类似结果。

详情请上门,例如。 学习你。

问题回答

由于你提到GHCi,你指出,你也可以迅速执行IO行动,并通过<代码><-将行动的价值与名称挂钩。

a <- randomRIO (0, 10)
a + 2

然而,我建议你通过传译读Anthony和hammar之间的联系。 它更详细地解释了上述辛加(和其他操纵分子价值的方法)。





相关问题
Weighted random numbers

I m trying to implement a weighted random numbers. I m currently just banging my head against the wall and cannot figure this out. In my project (Hold em hand-ranges, subjective all-in equity ...

Comprehensive information about hash salts

There are a lot of questions about salts and best practices, however most of them simply answer very specific questions about them. I have several questions which feed into one another. Assuming a ...

Generate unique names?

I am working on a php site in which we have to upload images from users.i have to rename that file for preventing conflicts in the name of the image. uniqid(rand(), true); and adding a large random ...

How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

热门标签