Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aliasing function in Haskell

The following code doesn't compile:

import Data.Bits
xor2 = xor

However, once I added the type info, it compiles:

import Data.Bits
xor2 :: Bits a => a->a->a
xor2 = xor

I can't explain this. Any explanations?

like image 736
haskell looks great Avatar asked Dec 24 '22 23:12

haskell looks great


1 Answers

This is a problem with the dreaded monomorphism restriction (MMR), which is enabled by default. The MMR is a rule that forces top-level bindings that do not look like functions (ie x = ... vs x a = ...) to have monomorphic bindings unless they have an explicit polymorphic type signature.

The problem is that Bits a => a -> a -> a is polymorphic (note the type variable a), and Haskell does not know how to choose a default type for a that satisfies the Bits constraint.

Once you add a type signature, the MMR is appeased and you can have a top-level binding that's polymorphic. Another option is to "eta-expand" the definition by adding a named argument; since xor2 now syntactically looks like a function, the MMR does not apply:

xor2 x = xor x

You can also turn the MMR off with a language extension. You can put this at the top of your module:

{-# LANGUAGE NoMonomorphismRestriction #-}
like image 73
Tikhon Jelvis Avatar answered Jan 02 '23 12:01

Tikhon Jelvis