如何使用Exists类型约束

时间:2016-03-15 08:54:35

标签: purescript

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
     

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

1 个答案:

答案 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