假设一个人想对一组组合进行某种比较,例如:
combs [] r = [r]
combs (x:xs) r = combs xs (x:r) ++ combs xs r
answer = minimumBy (\a b -> compare (length . compress $ a)
(length . compress $ b)) list
where compress =
...something complicated involving values external to the list.
*Main> combs "ABCD" [] --Imagine a larger list of larger combinations.
["DCBA","CBA","DBA","BA","DCA","CA","DA","A",
"DCB","CB","DB","B","DC","C","D",""]
(实际的列表将是一个更复杂的字符串组合构造,但同样徒劳无功,并且任何列表x
都不会提供对总组合是否充分的洞察力)
如果列表变得非常大,在我们构造和丢弃不充分的组合时以某种方式更新一个结果,而不是在代表整个列表的值上调用比较会更有效吗?
例如,(伪)
loop = do c <- nextComb
if c > r then c else r
loop
在 Haskell 中如何做到这一点?或者 Haskell 的编译器会answer
通过自动丢弃列表的元素来优化值吗?或者我可能会错过的其他东西?