Search code examples
purescript

How to use type constrains with Exists


data Foo a = Foo a

I can create an array of Exists https://github.com/purescript/purescript-exists

[(mkExists (Foo 0)), (mkExists (Foo "x"))]

How can I use type classes? I want to get ["0", "x"]

getStrings :: Array (Exists Foo) -> Array String
getStrings list = map (runExists get) list
  where
  get :: forall a. Show a => Foo a -> String
  get (Foo a) = show a

No type class instance was found for

Prelude.Show _0

The instance head contains unknown type variables. Consider adding a type annotation.


Solution

  • One option is to bundle up the show function in your definition of Foo, something like this:

    import Prelude
    import Data.Exists
    
    data Foo a = Foo a (a -> String)
    
    type FooE = Exists Foo
    
    mkFooE :: forall a. (Show a) => a -> FooE
    mkFooE a = mkExists (Foo a show)
    
    getStrings :: Array FooE -> Array String
    getStrings = map (runExists get)
      where
      get :: forall a. Foo a -> String
      get (Foo a toString) = toString a
    
    --
    
    items :: Array FooE
    items = [mkFooE 0, mkFooE 0.5, mkFooE "test"]
    
    items' :: Array String
    items' = getStrings items