Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should a function be standalone and when should it be in a type class? Is it just a matter of taste?

Tags:

haskell

Take for example the fromIntegral function:

fromIntegral :: (Integral a, Num b) => a -> b

To check whether it is:

  • in the type class Integral
  • in the type class Num
  • in some other type class
  • standalone, not in any type class

We can use :info fromIntegral to find out.

It turns out it's standalone.

But why? Why wasn't it made to be part of either the Integral or Num typeclass (or some other typeclass)? Is there any good reason for it or is it more a matter of taste?

The answer for this example will help me answer the same question in general when designing my own custom type classes and functions.

like image 855
stackoverflowuser Avatar asked Jan 11 '23 03:01

stackoverflowuser


1 Answers

fromIntegral is defined as

fromIntegral = fromInteger . toInteger

The two functions are in Num and Integral classes respectively. When you include a function in a class, you're saying that it might to be defined differently for different types. fromIntegral does not.

like image 163
Karolis Juodelė Avatar answered Jan 31 '23 14:01

Karolis Juodelė