Skip to content

Instantly share code, notes, and snippets.

@aljce
Created November 20, 2017 07:37
Show Gist options
  • Save aljce/259424df8920944024835f79cb3cf6ae to your computer and use it in GitHub Desktop.
Save aljce/259424df8920944024835f79cb3cf6ae to your computer and use it in GitHub Desktop.
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
module Unsafe.Maybe where
import GHC.Prim (Addr#,nullAddr#,addrToAny#,anyToAddr#,eqAddr#,unsafeCoerce#)
import GHC.Magic (runRW#)
import GHC.Types (Any)
import Unsafe.Coerce (unsafeCoerce)
newtype Maybe a = UnsafeMaybe Any
just :: a -> Maybe a
just a = UnsafeMaybe (unsafeCoerce a)
nothing :: Maybe a
nothing = case addrToAny# nullAddr# of
(# m #) -> UnsafeMaybe m
maybe :: b -> (a -> b) -> Maybe a -> b
maybe n f (UnsafeMaybe pt) =
case runRW# (anyToAddr# pt) of
(# _, addr# #) -> case eqAddr# nullAddr# addr# of
0# -> case addrToAny# addr# of
(# a #) -> f a
_ -> n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment