1
data Foo a = Foo a

我可以创建一个https://github.com/purescript/purescript-exists数组Exists

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

如何使用类型类?我想得到["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

找不到类型类实例

Prelude.Show _0

实例头包含未知类型变量。考虑添加类型注释。

4

1 回答 1

3

一种选择是将函数捆绑show在您的定义中Foo,如下所示:

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
于 2016-03-15T11:45:00.950 回答