Contact/support | Changelog

First Class Dictionaries

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{-# LANGUAGE RecordWildCards, PolymorphicComponents #-}

import qualified Data.Map as M
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString      as B
import Data.Word

data MapLike m = MapLike {
    lookup :: Ord k => k -> m k a -> Maybe a   ,
    insert :: Ord k => k -> a -> m k a -> m k a,
    empty  :: forall k a . m k a               }

mapI :: MapLike M.Map
mapI = MapLike {
    lookup = M.lookup,
    insert = M.insert,
    empty  = M.empty }

-- Obviously you can use a shorter name for the "MapLike" constructor
foo x y z = let MapLike{..} = mapI in lookup x $ insert x y z

data ByteStringLike b = ByteStringLike { pack :: [Word8] -> b }

strict = ByteStringLike { pack = B.pack }
lazy   = ByteStringLike { pack = L.pack }

zot = (a, b) where
    a = pack [1, 2, 3] where ByteStringLike{..} = strict
    b = pack [1, 2, 3] where ByteStringLike{..} = lazy