停止这个函数递归的更方便的方法是什么?目前我使用嵌套的if/else,如果下一个组合“溢出”,则返回一个空列表。在这个函数中的习惯性哈斯克尔终止递归方式
nextcomb [] [] = []
nextcomb lst maxes | length lst == length maxes =
let lastel = last lst
in if lastel < last maxes
then (init lst) ++ [lastel+1]
else let higherbit = (nextcomb (init lst) (init maxes))
in if higherbit == []
then []
else higherbit ++ [1]
nextcomb lst maxes | otherwise = []
为了澄清,它的作用是它需要像[1,1,1,1]和增量它喜欢数字的列表:
[1,1,1,1] - > [1,1,1,2]
...
[1,1,1,9] - > [1,1,2,1]
...
[1,1,9,9] - > [1,2,1,1]
等
但是,第二个参数是一个列表,指示每列的最大值。因此,如果是马克塞斯[2,3],和初始列表是[1,1],则进展woudld是:
[1,1] - >并[1,2]
[1 ,2] - > [1,3]
[1,3] - >并[2,1]
[2,1] - > [2,2]
[2,2 ] - > [2,3]
[2,3] - > []
编辑:“小端”版本所推荐的chepner
nextcomb' [] [] = []
nextcomb' lst maxes | length lst /= length maxes = []
nextcomb' lst maxes =
let firstel = head lst
in if firstel < head maxes
then (firstel+1) : (tail lst)
else let higherbit = (nextcomb' (tail lst) (tail maxes))
in if higherbit == []
then []
else 1 : higherbit
请注意,使用颠倒的“低端”列表可能更容易,只能将它们显示为“big-endian”。 – chepner
注意到,好抓。谢谢。 –
为什么在最后一个例子中,最后一个数字不能是4,但第一个数字可以是2? – zakyggaps