buzzyso
buzzyso

Reputation: 47

Turn a simple recursive function into pattern matching

I'm a complete beginner so this is probably a stupid question. I want to turn this recursive function that sums all integers to a function with pattern matching

sumOfNumbers :: Int -> Int
sumOfNumbers n
   | n == 0        = 0
   | otherwise   = n + sumOfNumbers(n -1)  

Which I'm guessing would look like this.

sumOfNumbers :: Int -> Int
sumOfNumbers n == 0    = 0        
sumOfNumbers _  = n + sumOfNumbers(n -1) 

My attempt is wrong as a I get

Parse error in pattern

error. What's wrong?

Upvotes: 1

Views: 98

Answers (2)

Carlos Bazilio
Carlos Bazilio

Reputation: 960

When you use values on the left side of '=' the pattern matching appears:

sumOfNumbers :: Int -> Int
sumOfNumbers 0 = 0        
sumOfNumbers n = n + sumOfNumbers(n -1)

Upvotes: 2

Adam Smith
Adam Smith

Reputation: 54273

simple!

sumOfNumbers :: Int -> Int
sumOfNumbers 0 = 0        
sumOfNumbers n = n + sumOfNumbers(n-1)

The pattern you're matching is 0 or n.

Upvotes: 2

Related Questions