gpt4 book ai didi

haskell - 使用列表 monad 实现一个数字计数器

转载 作者:行者123 更新时间:2023-12-01 08:07:06 25 4
gpt4 key购买 nike

所以,我在看问题 here ,并为该问题建立了一个相当丑陋的解决方案。在尝试清理它时,我开始研究列表理解和列表 monad。我决定做的是使用列表 monad 实现一个数字计数器。给定一个输入数字序列 [1, 2],我想生成一个类似于以下内容的输出序列:

[ [ 0, 0],
[ 0, 1 ],
[ 0, 2 ],
[ 1, 0 ],
[ 1, 1 ],
[ 1, 2 ] ]

也就是说,我将遍历该范围内列表中所有元素的所有可能值。

haskell.org list monad documentation说:

The bound function is applied to all possible values in the input list and the resulting lists are concatenated to produce a list of all possible results.

太棒了!看起来很完美...这是我为生成解决方案而编写的代码:

count :: [Integer] -> [[Integer]]
count [] = []
count (x:xs) =
-- get all possible sequences for the remaining digits
let
remDigits :: [[Integer]]
remDigits = count xs
in
-- pull out a possible sequence for the remaining digits
do nextDigits <- remDigits
-- pull out all possible values for the current digit
y <- [0..x]
-- record that "current digit" : "remaining digits" is
-- a valid output.
return (y:nextDigits)

但是用任何东西调用 count 都会产生空列表,我不知道为什么。我错过了什么?

最佳答案

count = sequence . map (enumFromTo 0)

是的,就这么简单。试一试:)

关于haskell - 使用列表 monad 实现一个数字计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1856071/

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