data Foo a = Foo a
我可以创建一个Exists
https://github.com/purescript/purescript-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
实例头包含未知类型变量。考虑添加一个 类型注释。
答案 0 :(得分:2)
一种选择是在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