user2913495
user2913495

Reputation:

How to use Integral/Fractional functions with Num

(I am rather new to Haskell, and to functional programming in general so may be doing things completely wrong)

I am building a puzzle in Haskell, and have been told that forcing the least as possible is the best (type-wise). So instead of making things of an Integral type, or a Fractional type, I am using a parametrized type:

data Orthotope a = Orthotope ...

and in almost all functions I use the class constraint

(Num a)=> ...
(Num a,Ord a)=> ...

however, In some specific functions I need division (and once sqrt). I am aware I can use (/) for Fractional, and div for Integral, (fromIntegral where needed) and even that I can use Data.Typeable to check which it is, but have been told that that is almost always the completely wrong approach.

Is there a better way to division and sqrt, on a type which isn't completely known? Or is this a case where I should use tests on the type itself?

(I am trying to find a way to be able to do something to Also Fractional's and also Integral', and if it works on more types, even better. (as opposed to using a less general type))

thanks.

Upvotes: 0

Views: 182

Answers (2)

Daniel Wagner
Daniel Wagner

Reputation: 153102

Having a single operation which does "nearly exact" division on types that support it and rounding-down-division on types that can only represent whole numbers is a common source of bugs in other languages. I would propose that you keep the distinction that Haskell has, by offering different operations on those two classes of types, and force the user to consciously choose between rounding division and more standard division.

Upvotes: 1

ErikR
ErikR

Reputation: 52049

Floating would be the most general type which supports both sqrt and division.

You can have ghci tell you this by defining a function which uses both and having ghci tell you what its type is:

ghci> let f x y = sqrt x / y
ghci> :t f
f :: Floating a => a -> a -> a

Also, note that div is not exactly the same as / since the former rounds the result to always return an integer.

Upvotes: 0

Related Questions