Skip to content

Instantly share code, notes, and snippets.

@ncfavier
Created February 17, 2023 16:43
Show Gist options
  • Save ncfavier/6dfe5bc3778350d58df8505815664706 to your computer and use it in GitHub Desktop.
Save ncfavier/6dfe5bc3778350d58df8505815664706 to your computer and use it in GitHub Desktop.
Identity function with special treatment to Bool values, by @Player-205
{-# LANGUAGE MagicHash, UnboxedTuples #-}
import GHC.Prim
import Unsafe.Coerce
import Prelude hiding (id)
main :: IO ()
main = do
print (id True)
print (id False)
print (id 15)
print (id 13.47)
print (id "one, two, three")
print (id (True, False))
id :: a -> a
id !a = case (# eqT, eqF #) of
(# 0#, 1# #) -> t
(# 1#, 0# #) -> f
_ -> a
where
eqT = reallyUnsafePtrEquality# a t
eqF = reallyUnsafePtrEquality# a f
!t = unsafeCoerce True
!f = unsafeCoerce False
@ncfavier
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment