Const.hs 2.33 KB
Newer Older
1
2
3
4
5
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
6
{-# LANGUAGE Trustworthy #-}
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

-----------------------------------------------------------------------------
-- |
-- Module      :  Data.Functor.Const
-- Copyright   :  Conor McBride and Ross Paterson 2005
-- License     :  BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer  :  libraries@haskell.org
-- Stability   :  experimental
-- Portability :  portable

-- The 'Const' functor.
--
-- @since 4.9.0.0

module Data.Functor.Const (Const(..)) where

24
import Data.Bits (Bits, FiniteBits)
25
import Data.Foldable (Foldable(foldMap))
26
import Foreign.Storable (Storable)
27

28
import GHC.Arr (Ix)
29
import GHC.Base
30
import GHC.Enum (Bounded, Enum)
31
import GHC.Float (Floating, RealFloat)
32
import GHC.Generics (Generic, Generic1)
33
34
import GHC.Num (Num)
import GHC.Real (Fractional, Integral, Real, RealFrac)
35
36
37
38
39
import GHC.Read (Read(readsPrec), readParen, lex)
import GHC.Show (Show(showsPrec), showParen, showString)

-- | The 'Const' functor.
newtype Const a b = Const { getConst :: a }
40
41
42
    deriving ( Bits, Bounded, Enum, Eq, FiniteBits, Floating, Fractional
             , Generic, Generic1, Integral, Ix, Monoid, Num, Ord, Real
             , RealFrac, RealFloat , Storable)
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

-- | This instance would be equivalent to the derived instances of the
-- 'Const' newtype if the 'runConst' field were removed
instance Read a => Read (Const a b) where
    readsPrec d = readParen (d > 10)
        $ \r -> [(Const x,t) | ("Const", s) <- lex r, (x, t) <- readsPrec 11 s]

-- | This instance would be equivalent to the derived instances of the
-- 'Const' newtype if the 'runConst' field were removed
instance Show a => Show (Const a b) where
    showsPrec d (Const x) = showParen (d > 10) $
                            showString "Const " . showsPrec 11 x

instance Foldable (Const m) where
    foldMap _ _ = mempty

instance Functor (Const m) where
    fmap _ (Const v) = Const v

instance Monoid m => Applicative (Const m) where
    pure _ = Const mempty
    (<*>) = coerce (mappend :: m -> m -> m)
-- This is pretty much the same as
-- Const f <*> Const v = Const (f `mappend` v)
-- but guarantees that mappend for Const a b will have the same arity
-- as the one for a; it won't create a closure to raise the arity
-- to 2.