Void.hs 2.08 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE StandaloneDeriving #-}

-----------------------------------------------------------------------------
-- |
-- Copyright   :  (C) 2008-2014 Edward Kmett
-- License     :  BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer  :  Edward Kmett <ekmett@gmail.com>
-- Stability   :  provisional
-- Portability :  portable
--
-- A logically uninhabited data type, used to indicate that a given
-- term should not exist.
--
19
-- @since 4.8.0.0
20 21 22 23 24 25 26 27 28 29 30
----------------------------------------------------------------------------
module Data.Void
    ( Void
    , absurd
    , vacuous
    ) where

import Control.Exception
import Data.Data
import Data.Ix
import GHC.Generics
31
import Data.Semigroup (Semigroup(..), stimesIdempotent)
32 33 34

-- | Uninhabited data type
--
35
-- @since 4.8.0.0
36 37 38 39
data Void deriving (Generic)

deriving instance Data Void

40
-- | @since 4.8.0.0
41 42 43
instance Eq Void where
    _ == _ = True

44
-- | @since 4.8.0.0
45 46 47 48 49
instance Ord Void where
    compare _ _ = EQ

-- | Reading a 'Void' value is always a parse error, considering
-- 'Void' as a data type with no constructors.
50
-- | @since 4.8.0.0
51 52 53
instance Read Void where
    readsPrec _ _ = []

54
-- | @since 4.8.0.0
55 56 57
instance Show Void where
    showsPrec _ = absurd

58
-- | @since 4.8.0.0
59 60 61 62 63 64
instance Ix Void where
    range _     = []
    index _     = absurd
    inRange _   = absurd
    rangeSize _ = 0

65
-- | @since 4.8.0.0
66 67
instance Exception Void

68 69 70 71 72
-- | @since 4.9.0.0
instance Semigroup Void where
    a <> _ = a
    stimes = stimesIdempotent

73 74 75
-- | Since 'Void' values logically don't exist, this witnesses the
-- logical reasoning tool of \"ex falso quodlibet\".
--
quchen's avatar
quchen committed
76 77 78 79 80 81 82 83
-- >>> let x :: Either Void Int; x = Right 5
-- >>> :{
-- case x of
--     Right r -> r
--     Left l  -> absurd l
-- :}
-- 5
--
84
-- @since 4.8.0.0
85 86 87 88 89 90
absurd :: Void -> a
absurd a = case a of {}

-- | If 'Void' is uninhabited then any 'Functor' that holds only
-- values of type 'Void' is holding no values.
--
91
-- @since 4.8.0.0
92 93
vacuous :: Functor f => f Void -> f a
vacuous = fmap absurd