[英]Haskell non-tail recursion
我想知道這是否代表尾遞歸。 如果不是我怎么能這樣做。
countP :: [a] -> (a->Bool) -> Int
countP [] _ = 0
countP (x:xs) p = countP_aux (x:xs) p 0
countP_aux [] _ _ = 0
countP_aux (x:xs) p acumul
|p x==True = (countP_aux xs p (acumul))+1
|otherwise = (countP_aux xs p (acumul))
countP [1,2,3] (>0)
3
(72 reductions, 95 cells)
此練習顯示列表中有多少值由p條件驗證。 謝謝
由於這不是尾遞歸
(countP_aux xs p (acumul))+1
尾調用應返回遞歸調用的結果,而不是使用遞歸調用的結果進行計算。
您可以使用累加器將非尾遞歸函數轉換為尾遞歸,您可以在其中執行其他工作,即
假設你有一個簡單的計數功能
f a
| a < 1 = 0
| otherwise = f (a-1) + 1
你可以像往常那樣使尾遞歸:
f' acc a =
| a < 1 = acc
| otherwise = f' (acc + 1) (a-1)
f = f' 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.