簡體   English   中英

Haskell中的遞歸加法

[英]Recursive addition in Haskell

問題:

給您一個函數plusOne x = x + 1 不使用任何其他(+) ,定義遞歸函數addition ,以使addition xyxy在一起。

(來自wikibooks.org

我的代碼(不起作用-無限循環):

plusOne x = x + 1

addition x y 
  | x > 0  =  addition (plusOne y) (x-1)
  | otherwise = y

問題:

  1. 如何將plusOne函數連接到addition遞歸函數?
  2. 應該怎么寫?

您在遞歸情況下混合了xy

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM