Created
November 20, 2017 07:37
-
-
Save aljce/259424df8920944024835f79cb3cf6ae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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