gpt4 book ai didi

haskell - 在一个 monad 中绑定(bind)一个函数 n 次

转载 作者:行者123 更新时间:2023-12-04 23:59:05 26 4
gpt4 key购买 nike

我已经看到使用 iterate 的解决方案或 replicate为了应用函数n次。但是,我没有设法在 State monad 中使用它。

此代码有效:

-- Stuff an empty game level with obstacles.
generateLevel :: Level -> State StdGen Level
generateLevel lvl =
placeRandomWall lvl >>= placeRandomWall >>= placeRandomWall

不出所料,这个也有效:
generateLevel :: Level -> State StdGen Level
generateLevel lvl =
placeRandomWall =<< placeRandomWall =<< placeRandomWall lvl

但是,这与以下内容不同:
generateLevel :: Level -> State StdGen Level
generateLevel lvl =
(placeRandomWall =<< placeRandomWall =<< placeRandomWall) lvl

最新的提示类型。因此,我不能 foldl (=<<) id (relicate 42 placeRandomWall) ,我也不能 iterate .

这是有道理的,因为迭代需要 a -> a功能,而我拥​​有的是 a -> m a或类似的东西。所以,我真的不知道如何从那里去。

最佳答案

我想你正在寻找 <=<>=>来自 Control.Monad .它们可以折叠在您使用 replicate 创建的列表中创建一个大 Action 。

试试 foldr (<=<) return (replicate 42 placeRandomWall) .

关于haskell - 在一个 monad 中绑定(bind)一个函数 n 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13042863/

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