我試圖做到這一點如何創建一個具有多態數據的數組?
data Foo a = Foo a
data FooWrapper = FooWrapper (forall a. Foo a)
foo = [FooWrapper (Foo 0), FooWrapper (Foo "")]
但有一個錯誤
無法比擬型
Int
型
a0
我試圖做到這一點如何創建一個具有多態數據的數組?
data Foo a = Foo a
data FooWrapper = FooWrapper (forall a. Foo a)
foo = [FooWrapper (Foo 0), FooWrapper (Foo "")]
但有一個錯誤
無法比擬型
Int
型
a0
存在類型在PureScript中與在Haskell中不完全相同,因此通常我們使用purescript-exists
庫來處理這類事情。
等效採用Exists
是:
import Data.Exists (Exists(), mkExists)
data Foo a = Foo a
data FooWrapper = FooWrapper (Exists Foo)
foo = [FooWrapper (mkExists (Foo 0)), FooWrapper (mkExists (Foo ""))]
我在這種情況下,假設你也許並不需要FooWrapper
可言,可能只是有Exists Foo
陣列。
是否可以使用帶有'Exists'的類型約束? 'data FooWrapper = FooWrapper(forall a。Show a => Foo a)'例如,如何從[(mkExists(Foo 0)),(())獲得'[「0」,「」] mkExists(Foo「」))]'? – ais
是的,你需要以某種方式將字典添加到包裝類型中。另一種方法是使用'forall'對存在類型進行編碼,例如'輸入SomeShow = forall r。 (a。顯示a => a - > r) - > r'。 –
@PhilFreeman你能展示一個完整的'getStrings'代碼嗎?http://stackoverflow.com/questions/36006483/how-to-use-type-constrains-with-exists? – ais
你在做什麼?我問,因爲如果沒有對元素類型的某種約束,具有不同類型元素的數組將不會非常有用。這通常被認爲是Haskell中的反模式。 –
'data Foo ab = Foo ab''foo1 :: Foo Int String''foo2 :: Foo Int Int'我該如何創建一個可以與Foo數組一起工作的函數,即使它們的第二個參數具有不同的類型'doSomething [ foo1,foo2]',因爲函數只使用第一個參數。 – ais