如何对 Exists 使用类型约束
How to use type constrains with Exists
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
No type class instance was found for
Prelude.Show _0
The instance head contains unknown type variables. Consider adding a
type annotation.
一种选择是在 Foo
的定义中捆绑 show
函数,如下所示:
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
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
No type class instance was found for
Prelude.Show _0
The instance head contains unknown type variables. Consider adding a type annotation.
一种选择是在 Foo
的定义中捆绑 show
函数,如下所示:
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