我想重复应用一个函数simplify'
,直到结果“稳定”(即simplify'(x) == x
):
simplify :: Expr -> Expr
simplify expr =
let iterations = iterate simplify' expr
neighbours = zip iterations (tail iterations)
simplified = takeWhile (\(a, b) -> a /= b) neighbours
in snd $ last ((expr, expr) : simplified)
simplify' :: Expr -> Expr
这对我来说似乎是一个普遍的问题。有没有更优雅的解决方案?
更新:我找到了一个更简单的解决方案,但我仍在寻找更优雅的解决方案:)
simplify expr =
let next = simplify' expr
in if next == expr
then expr
else simplify next