Question

I came across the following code in GHC.Prim:

...

negateFloat# :: Float# -> Float#
negateFloat# = let x = x in x

-- |Truncates a @Float#@ value to the nearest @Int#@.
--     Results are undefined if the truncation if truncation yields
--     a value outside the range of @Int#@.

float2Int# :: Float# -> Int#
float2Int# = let x = x in x

expFloat# :: Float# -> Float#
expFloat# = let x = x in x

logFloat# :: Float# -> Float#
logFloat# = let x = x in x

...

In particular:

  1. float2Int# shouldn't even type check
  2. None of the functions take an argument and hence seem to be malformed
  3. None of the functions apply the mathematical operation they claim to
  4. All of the functions are "infinitely recursive": let x = x

I know the extension is called "MagicHash", but it can't be that magical. What gives?

(I guess I should add the disclaimer that I have no idea what -XMagicHash actually does, I just assumed it allowed the # syntax, and nothing more.)

Was it helpful?

Solution

The clue is at the top of the module:

{-
This is a generated file (generated by genprimopcode).
It is not code to actually be used. Its only purpose is to be
consumed by haddock.
-}

Incidentally, let x = x in x is equivalent to undefined, and is valid for any data type; x isn't constrained by being defined in any way other than self-referentially, so can be any type.

These functions are "primitive" meaning operations so basic they're not defined in Haskell code, and quite possibly just translated directly to machine instructions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top