[Haskell-cafe] How to abstract away set representation

Tom Ellis tom-lists-haskell-cafe-2013 at jaguarpaw.co.uk
Sun Mar 8 21:01:59 UTC 2015


On Sun, Mar 08, 2015 at 09:52:50PM +0100, martin wrote:
> Hello all,
> 
> I was trying to construct a data type "Profile" which allows some set-like
> behavior.  I started with functions to count, add and filter profiles.
> 
> type Count = Int
> 
> 
> data Prof a = P {
>         pCount  :: Count,
>         pFilter :: (a -> Bool) -> Prof a,
>         pAdd    :: (Prof a) -> (Prof a)
>         } |
>         NoProfile
[...]
> What would be a good way to work with set-like behavior without being tied
> to one particular implementation?

How about

    data ProfOps prof = P {
        pCount  :: prof -> Count
        pFilter :: (a -> Bool) -> prof -> prof
        pAdd    :: prof -> prof
    }

Then you can instantiate this package of operations at different types, for
example

    listProf :: ProfOps [a]
    listProf = P {
      pCount  = length,
      pFilter = filter,
      pAdd    = (++)
    }

If you really want the type parameter to be exposed you can use

    data ProfOps prof = P {
        pCount  :: forall a. prof a -> Count
        pFilter :: forall a. (a -> Bool) -> prof a -> prof a
        pAdd    :: forall a. prof a -> prof a
    }

Tom


More information about the Haskell-Cafe mailing list