Jump to content

Need help with a simple problem on Haskell

- - - - -

  • Please log in to reply
3 replies to this topic

#1
NobleJms

NobleJms

    Newbie

  • Members
  • Pip
  • 2 posts
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!!

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
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
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
NobleJms

NobleJms

    Newbie

  • Members
  • Pip
  • 2 posts
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

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
What does Div 1 3 give you?
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users