How to use type constrains with Exists

。_饼干妹妹 提交于 2019-12-23 03:51:08

问题


data Foo a = Foo a

I can create an array of Exists https://github.com/purescript/purescript-exists

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

How can I use type classes? I want to get ["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.


回答1:


One option is to bundle up the show function in your definition of Foo, something like this:

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


来源:https://stackoverflow.com/questions/36006483/how-to-use-type-constrains-with-exists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!