Search code examples
purescript

How can I create an array with polymorphic data?


I am trying to do this

data Foo a = Foo a
data FooWrapper = FooWrapper (forall a. Foo a)

foo = [FooWrapper (Foo 0), FooWrapper (Foo "")]

But there is an error

Could not match type

Int

with type

a0

Solution

  • Existential types don't quite work the same in PureScript as they do in Haskell, so usually we use the purescript-exists library for this kind of thing.

    The equivalent using Exists would be:

    import Data.Exists (Exists(), mkExists)
    
    data Foo a = Foo a
    data FooWrapper = FooWrapper (Exists Foo)
    
    foo = [FooWrapper (mkExists (Foo 0)), FooWrapper (mkExists (Foo ""))]
    

    I suppose in this case you probably don't need FooWrapper at all and could just have an array of Exists Foo.