如何制作一个randApply
函数,其中包含种子x
和一系列函数(a -> a
类型,f
,g
, h
)从f
,g
,h
的排列中返回一个随机的
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
?
答案 0 :(得分:0)
首先,您不打算使用随机值创建函数randApply :: a -> [a -> a] -> a
。而是定义一个randApply :: a -> [a -> a] -> IO a
。在https://wiki.haskell.org/Monad了解Monad
。
解决方案的2个步骤:
随机:
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)