如何在纯函数中选择一个随机列表元素? [英] How to pick a random list element in a pure function?

查看:90
本文介绍了如何在纯函数中选择一个随机列表元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个Haskell函数,它可以从给定列表中挑选出一个随机数。
我的类型签名是:

I want to make a Haskell function that can pick out a random number from a given list. My type signature is:

randomPick :: [a] -> a 

我该怎么办?

What should I do?

推荐答案

Haskell中纯函数的定义部分是 引用透明 ,即与评估结果互换。这意味着评估结果必须每次都一样。埃尔戈,恐怕你想要的功能是不可能的。要在Haskell中生成随机数,函数需要做以下两件事之一:

Part of the definition of a "pure" function in Haskell is that it is referentially transparent, that is, interchangeable with the result of evaluating it. This implies that the result of evaluating it must be the same every time. Ergo, the function you want isn't possible, I'm afraid. To generate random numbers in Haskell, a function needs to do one of two things:

取出并返回伪随机数生成器,例如:

Take and return a pseudorandom number generator, e.g.:

randomPick :: RNG -> [a] -> (a, RNG)

或者使用 IO 从外部世界访问随机性:

Or use IO to access randomness from "the outside world":

randomPick :: [a] -> IO a

两种样式均由模块 System.Random 。同样,在前一种情况下,传递PRNG可以使用 State monad或者特殊用途随机monad

Both styles are provided by the module System.Random. Also, in the former case, passing the PRNG around can be abstracted out using the State monad, or perhaps a special-purpose Random monad.

这篇关于如何在纯函数中选择一个随机列表元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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