簡體   English   中英

haskell —一個實例函數聲明中的一個訪問類型變量可以嗎?

[英]haskell — can one access type variables from an instance function declaration?

我想訪問實例中的類型變量,這些變量不會顯示在實例的參數中。 例如,

class A a where foo :: a b
data C a
instance A C where
    foo :: forall b. C b
    foo = undefined :: C b

當然,上面的方法可以在沒有作用域類型表達式的情況下解決,但是我有一個非玩具示例,我實際上需要它。

編輯

請在粘貼代碼作為答案之前嘗試您的代碼! 以上(丹尼爾的答案)導致

Test.hs:51:5: Misplaced type signature: foo :: forall b. C b
Failed, modules loaded: none.

我認為,要克服Daniel的解決方案的問題,即不允許您為類型類函數提供簽名,您可以簡單地定義一個頂級函數,並在類型類的實例中對其“重命名”。 在您的簡單示例中,以下應該可以工作。

{-# LANGUAGE ScopedTypeVariables #-}

class A a where 
    foo :: a b

instance A C where
    foo = foo'

foo' :: C b
foo' = undefined :: C b

盡管最好使用實際解決方案,但可以使用asTypeOf並添加虛擬參數來解決該問題。 這是一個例子

class A a where foo2 :: b -> a b -- added parameter b
data C a
instance A C where
    foo2 x = undefined `asTypeOf` (wrapA x)

wrapA :: A C => a -> C a
wrapA = undefined

foo :: A a => a b
foo = foo2 undefined

對於我的真實示例,這確實起作用。 干杯!

我認為在課堂上的聲明

class A a where
    foo :: a b

foo的類型是真的

forall b. a b

foo應該與b類型無關。 或者, b實際上不是AA一部分。 所以...我不認為您應該能夠引用它嗎? 盡管我可能不太了解...也許您可以在必要的地方舉一個例子?

如果您需要在一個以上的方法中保持相同的類型,則可以使用多參數類型類:

class A a b where
    foo :: a b
    bar :: a b
{-# LANGUAGE ScopedTypeVariables #-}
class A a where foo :: a b
instance A C where
    foo :: forall b. C b
    foo = undefined :: C b

閱讀更多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM