Haskell从数据类型中随机 [英] Haskell Random from Datatype

查看:144
本文介绍了Haskell从数据类型中随机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Haskell来说,我很新。
我有一个数据类型:

  data句子= Prop Int 
|没有句子
|和[句子]
|或[语句]
导出Eq

我已经为它写了一个Show实例



然而,无论是否合理,我都希望能够生成一个随机的句子。
如何在Haskell中完成这项工作?

解决方案

随机数生成是不纯操作的典型示例,因为调用一个随机生成器两次当然会产生不同的结果 - Haskell的本性不允许这样做。

因此,您需要使用一个所谓的monad Gen a 代表一个随机生成器,运行时产生一个类型为 a 的值。 >

幸运的是,您可以将这些生成器以相当好的语法组合起来......

所以,你只需要一些,它实现了这样一个生成器 - 现在我们开始吧。

  randomNo =无< $> randomSentence 
randomProp = Prop< $>选择(1,10)
[...]

randomSentence = oneOf [randomNo,randomProp,...]


Im pretty new to Haskell. I have a datatype:

data Sentence= Prop Int
          | No Sentence
          | And [Sentence]
          | Or [Sentence]
          deriving Eq

I already wrote a Show instance for it

However, whether it makes sense or not, I would like to be able to generate a random Sentence. How can i accomplish this in Haskell?

解决方案

Random number generation is a typical example of an "impure" operation, since calling a random generator twice will of course yield different results - Haskell's nature disallows this.

Therefore, you need to use a so called monad Gen a that represents a random generator, that, when run, yields a value of type a.

Fortunately, you can combine these generators in a quite nice syntax ...

So, you just need some library that implements such a generator - and here we go.

randomNo   = No <$> randomSentence
randomProp = Prop <$> choose (1, 10) 
[...]

randomSentence = oneOf [randomNo, randomProp, ...]

这篇关于Haskell从数据类型中随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆