[英]Haskell - Branch within recursive loop executes all previously visited branches in addition to the chosen one
[英]Recursive addition in Haskell
問題:
給您一個函數
plusOne x = x + 1
。 不使用任何其他(+)
,定義遞歸函數addition
,以使addition xy
將x
和y
在一起。
(來自wikibooks.org )
我的代碼(不起作用-無限循環):
plusOne x = x + 1
addition x y
| x > 0 = addition (plusOne y) (x-1)
| otherwise = y
問題:
plusOne
函數連接到addition
遞歸函數? 您在遞歸情況下混合了x
和y
addition x y | y > 0 = addition (plusOne x) (y - 1) -- x + y == (x + 1) + (y - 1)
| otherwise = x -- x + 0 = x
使用==
和0
addition = add 0 where
add a y x | a == y = x
| otherwise = add (plusOne a) y (plusOne x)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.