Null Pointer Pattern

Andrew Martin andrew.thaddeus at gmail.com
Mon Aug 17 14:43:52 UTC 2020


Foreign.Ptr provides nullPtr. It would make some of my code more terse if
this was additionally provided as a pattern synonym. The pattern synonym
can be defined as:

    {-# language ViewPatterns #-}
    {-# language PatternSynonyms #-}
    module NullPointerPattern
      ( pattern Null
      ) where
    import Foreign.Ptr (Ptr,nullPtr)
    pattern Null :: Ptr a
    pattern Null <- ((\x -> x == nullPtr) -> True)
      where Null = nullPtr

Any here is example of code that becomes more terse once this is available:

    foo :: IO (Either Error (Ptr Foo))
    foo = do
      p <- initialize mySettings
      if p == nullPtr
        then pure (Left InitializeFailure)
        else pure (Right p)

With the pattern synonym, we are able to take advantage of LambdaCase:

    foo :: IO (Either Error (Ptr Foo))
    foo = initialize mySettings >>= \case
      Null -> pure (Left InitializeFailure)
      p -> pure (Right p)

I'm curious what others think.

-- 
-Andrew Thaddeus Martin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/libraries/attachments/20200817/807e90e2/attachment.html>


More information about the Libraries mailing list