我的递归挂了

时间:2012-11-13 17:37:33

标签: haskell recursion

它编译正确,但不起作用。

它适用于[],但如果它还有其他任何东西它只会永远挂起。 test1 - 好的,test 2挂起。

--Tests pour 'effectuerAchat'.
test1 = effectuerAchat achat1_1 [] == ([],achat1_1)
test2 = effectuerAchat achat1_1 [offre1_1_1_100] == ([(Commande "fournisseur1" "article1" 1 100)],Achat "article1" 0)

这是代码......

effectuerAchat a os = rfred a (offresPour a os) (achatQuantite(a)) []
   where rfred a os n lc = 
            if os == []|| n==0
            then (lc,(Achat (achatArticle(a)) n))
            else 
                 if n>=(offreQuantite(head(os)))
                 then let c= (Commande (offreFournisseur(head(os))) (achatArticle(a)) (offreQuantite(head(os))) (offrePrix(head(os))))
                          n= n-(offreQuantite(head(os)))
                          xs =  tail(os)
                      in  rfred a xs n (c:lc)
                 else let c= (Commande (offreFournisseur(head(os))) (achatArticle(a)) n (offrePrix(head(os))))
                          n= 0
                          xs =  tail(os) 
                      in  rfred a xs n (c:lc)

1 个答案:

答案 0 :(得分:4)

中有无限循环
let c= (Commande (offreFournisseur(head(os))) (achatArticle(a)) (offreQuantite(head(os))) (offrePrix(head(os))))
    n= n-(offreQuantite(head(os)))
    ^^^^^

右侧的n不是上面测试中的n,而是绑定左侧引入的n(它隐藏了一个来自外部范围)。如果os (= offresPour achat1_1 [offre1_1_1_100])包含多个项目,则测试中需要n

if os == []|| n==0

在递归调用中,评估挂起。

以不同方式命名变量,

let c = ...
    n' = n - ...
in rfred ... n' ...
相关问题