以随机顺序嵌套调用

时间:2016-11-29 15:34:56

标签: algorithm haskell

如何制作一个randApply函数,其中包含种子x和一系列函数(a -> a类型,fgh)从fgh的排列中返回一个随机的

  • f (g (h x))
  • f (h (g x))
  • g (f (h x))
  • g (h (f x))
  • h (f (g x))
  • h (g (f x))

如何定义此类randApply :: a -> [a -> a] -> a

1 个答案:

答案 0 :(得分:0)

首先,您不打算使用随机值创建函数randApply :: a -> [a -> a] -> a。而是定义一个randApply :: a -> [a -> a] -> IO a。在https://wiki.haskell.org/Monad了解Monad

解决方案的2个步骤:

  1. 随机播放功能
  2. 逐个将随机功能列表应用于种子
  3. 随机:

    shuffle :: [a] -> IO [a]
    shuffle [] = return []
    shuffle xs = do nRand <- randomRIO (0, length xs - 1)
                    rest  <- shuffle (erase nRand xs)
                    return (xs !! nRand : rest)
    
    erase :: Int -> [a] -> [a]
    erase n xs = take n xs ++ drop (n+1) xs
    

    https://wiki.haskell.org/Random_shuffle检查更有效的随机播放程序。

    逐一申请种子:

    seqApply :: a -> [a -> a] -> a
    seqApply x []          = x
    seqApply x (f : fList) = seqApply (f x) fList
    

    你想要的randApply:

    randApply :: a -> [a -> a] -> IO a
    randApply x fList = do randList <- shuffle fList
                           return (seqApply x randList)