Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fractional type is in Haskell

Tags:

haskell

I want to use rational number type instead of factional type in Haskell (or float/double type in C)

I get below result:

8/(3-8/3)=23.999...
8/(3-8/3)/=24

I know Data.Ratio. However, it support (+) (-) (*) (/) operation on Data.Ratio:

1%3+3%3 == 4 % 3
8/(3-8%3) == 24 % 1

I had checked in Racket:

(= (/ 8 (- 3 (/ 8 3))) 24)
#t

What's correct way to ensure 8/(3-8/3) == 24 in Haskell?

like image 248
liuyang1 Avatar asked Jan 27 '23 17:01

liuyang1


1 Answers

Use an explicit type somewhere in the chain. It will force the entire calculation to be performed with the corrrect type.

import Data.Ratio

main = do
    print $ 8/(3-8/3) == 24
    print $ 8/(3-8/3) == (24 :: Rational)

Prints

False
True
like image 130
n. 1.8e9-where's-my-share m. Avatar answered Feb 03 '23 13:02

n. 1.8e9-where's-my-share m.