I need to write the function product in two ways:
- Using Guards
- Using if-then-else
So that the function return the product of m through n.
example:
product 3 5
returns 3*4*5 = 60
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This sounds like a homework problem so instead of just dropping code on you, let’s work through the problem:
Type Signature
Haskell is a functional language with strong typing so it is probably best to start by writing the type signature of our function. Your example shows two integer arguments and an integer return value. We code this as:
This reads as “
productis a function that takes twoInts and returns anInt.” (there are other more correct ways to read this but that is for another day)Recursion
we are going to use a common pattern in Haskell. Because we need to keep track of intermediate values in this case the partial product we will write a second function
product'that will take an extra parameter, the running product.At every iteration this will take the most recent accumulated value multiply by current and pass that as the new accumulator, it will take current and add 1 to it passing it as the new current, and will pass final unchanged. To get it started we write our original function:
or in points-free notation
The problem is the
product'code will loop forever. We need a way to stop when we current is greater then final.Guards
Rather then rewrite the book on guard patterns I’ll send you to the book. In short they let you a boolean before you do something. We’ll use them to stop our recursion.
So long as
currentis less than or equal tofinalwe continue to recurse once it’s not the final answer is in accumulator.If-Then-Else
Guards can be replaced with
ifconstructs (perhaps deeply nested) in a mechanical fashion.Final Thoughts
Don’t write code like this. There are a number of wonderfully generic higher level function that do just these types of things. Here is just one better way to write product: