Atir
Atir

Reputation: 163

Recursive addition in Haskell

The problem:

You are given a function plusOne x = x + 1. Without using any other (+)s, define a recursive function addition such that addition x y adds x and y together.

(from wikibooks.org)

My code (it does not work -- endless loop):

plusOne x = x + 1

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

Questions:

  1. How to connect the plusOne function to the addition recursive function?
  2. How should it be written?

Upvotes: 0

Views: 1450

Answers (2)

Luka Rahne
Luka Rahne

Reputation: 10447

using == and 0

addition = add 0 where
    add a y x | a == y = x
              | otherwise = add (plusOne a) y (plusOne x)

Upvotes: 0

chepner
chepner

Reputation: 530843

You are mixing up x and y in your recursive case

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

Upvotes: 1

Related Questions