Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeclass methods with "dummy" argument

Tags:

haskell

The typeclass Data. Bits has a method isSigned :: a -> Bool that returns True if the type of the argument is a signed type. The docs explicitly say that the argument is ignored. There are other such methods like that in the typeclass; there are also other typeclasses that have such methods. My question: why this design choice? The value depends only on the type, so why not just:

isSigned :: Bool

As a follow-up: suppose I had a custom typeclass with a nullary method method :: Bool. Would there be any reason to change it and do as Data.Bits does, that is, method :: a -> Bool?

like image 803
G. Rodrigues Avatar asked Aug 02 '26 06:08

G. Rodrigues


1 Answers

In short, the argument is ignored at runtime, but the type of the argument is used during compilation to select the correct instance of isSigned to use at runtime.


Without the argument, there is no way to determine which instance should be used to resolve the value of something like isSigned :: Bool.

> class Foo a where isSigned :: Bool

<interactive>:1:19: error:
    • Could not deduce (Foo a0)
      from the context: Foo a
        bound by the type signature for:
                   isSigned :: forall a. Foo a => Bool
        at <interactive>:1:19-34
      The type variable ‘a0’ is ambiguous
    • In the ambiguity check for ‘isSigned’
      To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
      When checking the class method: isSigned :: forall a. Foo a => Bool
      In the class declaration for ‘Foo’

If you enable the TypeApplications and AllowAmbiguousTypes extensions, you could do something like this:

class Foo a where
    isSigned :: Bool

instance Foo Int where
    isSigned = True

instance Foo Char where
    isSigned = False

Using isSigned alone would still be an error, but you could use isSigned @Int or isSigned @Char to get the specific value for a given type.

Back to standard Haskell, we need some way to select which instance's isSigned value is needed, and we do that by defining a function whose argument type ties it to a particular instance. The value of the argument is ignored, but the type is used during type-checking and compilation to select the correct instance.

like image 113
chepner Avatar answered Aug 04 '26 19:08

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!