2 Replies - 2859 Views - Last Post: 25 March 2012 - 12:38 PM

#1 AphexBravia  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 09-March 12

Multiply fractions in Haskell

Posted 24 March 2012 - 05:55 PM

Hi,

I'm trying to write a simple program in Haskell that multiples to fractions together. I have the program working I just cannot get it to out the faction in its most simple form. I have the sum 4/10 * 15/14 which outputs 60/140 which is correct but I need the answer to be 3/7.

type Fraction = (Int, Int)

makeFraction:: Int -> Int -> Fraction
makeFraction _ 0 = error "Denominator is zero"
makeFraction numerator denominator =
  ((div numerator d), (div denominator d))
    where d = gcd numerator denominator

multiply:: Fraction -> Fraction -> Fraction
multiply (n1, d1) (n2, d2) = makeFraction (n1 * n2, d1 * d2)



As I said without the last makeFraction in the codes works but just outputs the 60/140.. Any help would be much appreciated.

Is This A Good Question/Topic? 0
  • +

Replies To: Multiply fractions in Haskell

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2010
  • View blog
  • Posts: 3,032
  • Joined: 21-June 11

Re: Multiply fractions in Haskell

Posted 25 March 2012 - 03:14 AM

You're calling makeFraction with a tuple as its argument, but you didn't define it to take a tuple. The way you defined it, you need to call it as makeFraction num denom, which in this case would mean makeFraction (n1 * n2) (d1 * d2).
Was This Post Helpful? 0
  • +
  • -

#3 ishkabible  Icon User is offline

  • spelling expret
  • member icon





Reputation: 1616
  • View blog
  • Posts: 5,707
  • Joined: 03-August 09

Re: Multiply fractions in Haskell

Posted 25 March 2012 - 12:38 PM

also, it seems worth noting that Haskell has a "Ratio" type-class and set of functions that go with it and that you only need to implement 4 simple functions for it to all work perfectly. all the basic data integer types already have classes implemented.

This post has been edited by ishkabible: 25 March 2012 - 12:41 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1