我目前正在使用反应香蕉学习 FRP,并想创建一个随机函数流。我想出了这个:
-- | take number generator, and some pulse event stream, generate random function stream
mkRandom :: (Random a,RandomGen g) => g -> Event t b -> Event t ((a,a) -> a)
mkRandom rng es = (\f -> \r -> fst $ f r) <$> (accumE first $ next <$> es)
where first = flip randomR rng
next _ prev range = randomR range g
where (a,g) = prev range
它似乎有效,我可以这样使用它:
randFuncs = mkRandom rnd (pulse 1000 time)
some = ($ (0,10::Int)) <$> randFuncs
但是,当然,当我尝试共享该流以生成不同类型的数字时:
some2 = ($ (0,10::Double)) <$> randFuncs
类型检查器抱怨,我理解。然后我尝试将函数概括为以下内容:
mkRandom :: (RandomGen g) => g -> Event t b -> Event t (forall a. Random a => (a,a) -> a)
然后 GHC 抱怨非法多态签名以及我是否想启用 ImpredicativeTypes。我做了很长一段时间试图注释所有内容以使其工作,但 GHC 总是抱怨它无法匹配类型。
我的问题是 - 有可能做我想做的事吗?我真的需要 ImpredicativeTypes 还是我做错了?
我认为 RankNTypes 应该足够了,但我还没有使用此类扩展的经验。
提前致谢!
编辑:
作为记录,现在我基于有用响应的解决方案是:
newtype RandomSource = Rand { getRand :: forall a. (Random a) => (a,a) -> [a] }
-- | take number generator and some pulse event stream, generate randomness stream
mkRandom :: RandomGen g => g -> Event t a -> Behavior t RandomSource
mkRandom rng es = fst <$> (accumB (next id (id,rng)) $ next <$> es)
where next _ (_,rng) = (Rand $ flip randomRs g1, g2)
where (g1,g2) = split rng
-- | take a rand. source, a range and a pulse, return stream of infinite lists of random numbers
randStream :: Random a => Behavior t RandomSource -> (a,a) -> Event t b -> Event t [a]
randStream funcs range pulse = ($ range) . getRand <$> funcs <@ pulse