Hey guys,
I’ve been asked to create Haskell functions for simple multiplication and division using only +, -, and recursion techniques. Basically it’s like asking you to define the meaning of a word without using the actual word in the sentence. I am new to functional programming so this is quite hard for me. After brainstorming for an hour and some trials and errors, I finally got the multiplication codes down:
mult n 0 = 0
mult n 1 = n
mult n m = n + (mult n (m - 1))
Thus mult 5 4
= 5 + mult 5 3
= 5 + 5 + mult 5 2
= 5 + 5 + 5 + mult 5 1
= 5 + 5 + 5 + 5 + 5
= 20
Bingo!
But how do you do division?! I’ve been thinking for hours and would rather hit my head against a brickwall. :crying: If you guys could help me with this I would really appreciate it!
Thanks in advance!!
3 replies to this topic
#1
Posted 21 June 2011 - 05:48 AM
|
|
|
#2
Posted 21 June 2011 - 09:29 AM
I'd start by doing integral division, so the following would be results:
5/4 = 1
4/5 = 0
Basically, ignore the decimal part of the result. You're going to do a count of how many times you can subtract the divisor from the dividend.
Consider 18/4:
18/4 -> 1+ (18-4)/4
18/4 -> 1 + 1 + (14-4)/4
18/4 -> 1 + 1 + 1 + (10-4)/4
18/4 -> 1 + 1 + 1 + 1 + (6-4)/4
since 2 is less than 4, you return 0 now
18/4 -> 1 + 1 + 1 + 1 + 0 = 4
5/4 = 1
4/5 = 0
Basically, ignore the decimal part of the result. You're going to do a count of how many times you can subtract the divisor from the dividend.
Consider 18/4:
18/4 -> 1+ (18-4)/4
18/4 -> 1 + 1 + (14-4)/4
18/4 -> 1 + 1 + 1 + (10-4)/4
18/4 -> 1 + 1 + 1 + 1 + (6-4)/4
since 2 is less than 4, you return 0 now
18/4 -> 1 + 1 + 1 + 1 + 0 = 4
#3
Posted 21 June 2011 - 08:06 PM
Thank you WingedPanther. This method works great! My final formula is:
Div 0 x = 0
Div x y = 1+ Div (x - y) y
So Div 20 5 = 4
Div 0 x = 0
Div x y = 1+ Div (x - y) y
So Div 20 5 = 4
#4
Posted 22 June 2011 - 04:21 AM
What does Div 1 3 give you?
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account

Back to top









