gpt4 book ai didi

haskell - 如何洗牌?

转载 作者:行者123 更新时间:2023-12-03 12:02:54 26 4
gpt4 key购买 nike

如何在不替换的情况下从一组数字( [1, 2, 3] )中采样,直到我点击 x ?
我的计划是洗牌[1, 2, 3]并在 x 处截取:

-- chopAt 3 [2, 3, 1] == [2, 3]
-- chopAt 3 [2, 1, 3] == [2, 1, 3]
-- chopAt 3 [3, 1, 2] == [3]
chopAt _ [] = []
chopAt x (y:ys)
| x /= y = y : chopAt x ys
| otherwise = [y]

但是我不知道如何洗牌(或理解 Monads)。
-- sample without replacement from [1, 2, 3] until one hits a 3
-- x <- shuffle [1, 2, 3]
-- print (chopAt 3 x)
main = do
-- shuffle [1, 2, 3]
print (chopAt 3 [1, 3, 2])

最佳答案

要对列表进行洗牌,请使用 random-shuffle图书馆:

import System.Random (newStdGen)
import System.Random.Shuffle (shuffle')

main = do
rng <- newStdGen

let xs = [1,2,3,4,5]

print $ shuffle' xs (length xs) rng

关于haskell - 如何洗牌?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14692059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com