Haskell / GHC: Unclear constructor deconstruction?

Here is a specific case of a general question that I am really asking: suppose I'm in the critical section of the code and I got the value

x :: Maybe Int 

I know this is Just Int , and not Nothing , but due to the code from my control, I cannot arrange to directly receive the actual Int . I want to make

 case x of Just i -> whatever i 

but I don’t want the GHC to insert any error checking or handling or transitions or anything else; just interpret the bits as if they are Just i and let me deal with the consequences.

Is it possible? (Yes, I know that this is something that cannot be done regularly.)

+6
source share
3 answers

Sometimes you can help the GHC find out that matching the GADT template is common by adding some template labels. I'm not quite sure why this sometimes helps, but it can. If you really want to be insecure, the way to do this is to make a more informative GADT than the one you are working with and insecurely coercing it. Something like that:

 data Shmaybe :: Bool -> * -> * where Noway :: Shmaybe ra Shucks :: a -> Shmaybe True a fromShucks :: ShMaybe True a -> a fromShucks (Shucks a) = a unsafeFromJust :: forall a . Maybe a -> a unsafeFromJust m = fromShucks (unsafeCoerce m :: Shmaybe True a) 

It is important that the constructors match in both types of arguments and order. Obviously, this is all absurdly unsafe and has no guarantees. Segmentation errors may occur.

+1
source

Consider using the YOLO typeclass https://gist.github.com/nkpart/8922083d3c18a8f777b8

 instance Yolo Maybe where yolo (Just x) = x 

NB: It was a joke. Use fromJust .

+1
source

I am aware of several possibilities, but all of them implicitly include code for throwing errors in the case of Nothing .

Unusual pattern:

 λ> let Just a = Just "hi" λ> a "hi" λ> let Just a = Nothing λ> a *** Exception: <interactive>:4:5-20: Irrefutable pattern failed for pattern Data.Maybe.Just a 

Non-flowing patterns:

 λ> let f (Just a) = a λ> f (Just "hi") "hi" λ> f Nothing *** Exception: <interactive>:6:5-18: Non-exhaustive patterns in function f 

fromJust (check and throw error):

 λ> fromJust (Just "hi") "hi" λ> fromJust Nothing *** Exception: Maybe.fromJust: Nothing 

You cannot use unsafeCoerce , because for all a internal representations of Maybe a and a different, and I don’t know how to tell GHC not to check other cases in an irrefutable picture.

Have you shown that this behavior is undesirable performance and that there are no other, easier optimizations? If you do not, I would not worry about that :)

+1
source

All Articles