haskell中的随机数.并改组列表 [英] Random numbers in haskell. And shuffling a list

查看:58
本文介绍了haskell中的随机数.并改组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,当给出列表时,该函数将以随机顺序返回lsit.

i am trying to write a function that when given a list would return a lsit in random order.

这就是我的想法(列表长度为52):生成介于1到52之间的随机数作为列表的该元素.

this is how i thought of doing it(the list is of length 52): generate random number between 1 and 52 take that element of the list.

a = [1,2,3..] !! getRandom 52

然后递归调用相同的函数..生成1到51之间的随机数,并在列表中调用我们选择的第一个元素.

then recursively call same function.. generate random number between 1 and 51 and call on list with first element we picked removed.

(删除[1,2,3 ..])!getRandom 51

以此类推..在将所有选择的元素放入列表后,我们得到了相同的列表,但被随机排序.这是我的随机数函数:

And so on..after puting all elements picked in a list we get same list but shuffled. This is my random number function:

getRandom :: Int -> IO Int
getRandom x = getStdRandom (randomR (1,x))

但是因为此函数返回IO Int而不是Int,所以我无法使用它从列表中获取随机元素.我在这里能做什么?

But because this function returns IO Int not Int I can't use it to take random element from a list. What can i do here?

在执行大学任务时,我需要洗净52张卡片.我们还没有通过Monads和高级内容.那么,有没有一种简便的方法可以列出52张卡并对其进行洗牌?

on a university task i need to shuffle a deck of 52 cards. We didn't trough Monads and advanced stuff yet. So, is there an easy way to take a list of 52 cards and shuffle it?

推荐答案

在haskell中,您不能凭空创建随机数.您可以从种子创建它,但是每次使用相同的种子时,都可以得到相同的随机数序列.

In haskell you cannot create a random number out of thin air. You can create it from a seed, but then you get the excat same sequence of random numbers each time you use the same seed.

或者您从外部世界获取种子.然后,您可以在每次运行程序时输入"不同的种子,或者让库从系统时间中选择一个种子,或者不管它是这样做的-您都可以在IO领域使用.如果走这条路线,那么您可以在IO操作中选择随机数,然后将其随机排列.改组本身将是一个纯粹的操作.然后,您可以将改组后的列表打印到IO,但无法逃避IO领域.

Or you take the seed from the outside world. Then you can "enter" a different seed each time you run the program, or you let a library pick one from the system time or however it does it - either way you are in IO-land. If you go this route, then you pick your random number inside an IO-operation and shuffle the list with it. The shuffling itself will be a pure operation. You can then print the shuffled list to IO, but you cannot escape IO-land.

如果此任务的重点是学习如何对列表进行混洗,那么只要正确地进行混洗(足够棘手),如何获得随机数就可能无关紧要.

If the focus of this task is to learn how to shuffle lists, then it probably doesn't matter much how you get your random number, as long as you get the shuffling right (which is tricky enough).

所以写一个函数

shuffle :: Int->[a]->[a]

其中第一个参数是随机种子.然后,您可以留在纯净土地上,并使用System.Random函数创建任意需要的随机数.如果您的程序在每次调用列表时都以完全相同的方式对列表进行洗牌,请不要失望.

where the first parameter is a random seed. You can then stay in pure-land and use the System.Random functions you create more random numbers if you need any. Don't be disappointed if your program shuffles the list in the exact same way whenever you call it.

这篇关于haskell中的随机数.并改组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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