Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if a function is stand-alone or part of a type class

Tags:

haskell

When I come across a function, is there a general way to determine if it's completely stand-alone or a part of a type class? For instance:

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

This is the method I have developed to find the answer:

  1. Go to GHCi and do :info on all the listed class constraints, in this case :info Integral and :info Num.
  2. Check if any of them lists the function.
  3. If it does, it's part of that type class. If it doesn't, it's a stand-alone function (which is the case for forIntegral).

Is my method sound? Does it work in general?

like image 387
stackoverflowuser Avatar asked May 07 '14 22:05

stackoverflowuser


2 Answers

You can do :info on the function directly.

Prelude> :info fromInteger
class Num a where
  ...
  fromInteger :: Integer -> a
        -- Defined in `GHC.Num'

Prelude> :info fromIntegral
fromIntegral :: (Integral a, Num b) => a -> b
        -- Defined in `GHC.Real'

As you see, fromInteger belongs to the Num typeclass, while fromIntegral does not.

like image 138
kqr Avatar answered Oct 13 '22 01:10

kqr


There's an easier way, compare the difference in output for :info fromIntegral and :info fromInteger:

> :info fromIntegral
fromIntegral :: (Integral a, Num b) => a -> b
        -- Defined in `GHC.Real'
> :info fromInteger
class Num a where
  ...
  fromInteger :: Integer -> a
        -- Defined in `GHC.Num'

See how fromInteger is specified as part of a type class, but fromIntegral is not? That's how you can tell.

like image 41
bheklilr Avatar answered Oct 13 '22 01:10

bheklilr