![](/img/trans.png)
[英]Can TimeDuration type be an instance of Semigroup and Monoid?
[英]Semigroup/Monoid/Group type class hierarchy in Haskell errors
我正在嘗試創建代數類型類的“層次結構”,如下所示:
class Semigroup a where
(.*) :: a -> a -> a
foldr1 (.*) = foldl1 (.*) -- GHCi error: "`foldr1' is not a (visible) method of class `Semigroup'"
class (Semigroup a) => Monoid a where
identity :: a
(.*) identity = id :: a -> a -- GHCi error: "`.*' is not a (visible) method of class `Monoid'"
class (Monoid a) => Group a where
inverse :: a -> a
因此,群是幺半群,而幺半群是半群。 但是,我收到錯誤,即類看不到其父 class 的功能。
這些錯誤困擾着我,因為我假設通過編寫(例如) class (Semigroup a) => Monoid a
class Monoid a
將能夠看到 function (.*)
此外,Prelude 中foldr1
的類型沒有限制,所以我假設foldr1
可以在這種情況下工作。
Haskell 不允許您根據條款聲明(或強制執行)方程式(就像您想要做的那樣)。 這是出於一個非常實際的原因:在像 Haskell 這樣豐富的編程語言中證明任意項之間的相等性是不可判定的。 檢查人工構建的證明通常是可以確定的,但在編程時必須編寫和跟蹤這些證明也有些煩人。
盡管如此,如果這是您想要定期做的事情,那么有些語言可以做到這一點; 要搜索的術語是“依賴類型”。 例如,Coq 和 Agda 可能是目前最流行的兩種依賴類型語言,每一種語言都可以讓編寫一種只由良好、守法的半群(或幺半群)存在的類型變得非常簡單。
我不確定你想做什么。
如果您嘗試在Semigroup
中為foldr1
提供默認值,在Monoid
中為(.*)
提供默認值,那么您不能。
foldr1
在 Prelude 中被定義為非類型類 function,所以你不能在Semigroup
中給它一個本地定義(.*)
是Semigroup
class 的一部分。 你可以在Semigroup
實例中給出它的值,你可以在Semigroup
class 中給出它的默認值,但你不能在Monoid
class(或Monoid
實例)中給出它的值如果您嘗試在Semigroup
中為(.*)
提供默認值,在Monoid
中為identity
提供默認值,那么您使用的語法錯誤。
而是嘗試類似的東西
class Semigroup a where
(.*) :: a -> a -> a
(.*) = {-something-}
或者
class Semigroup a where
(.*) :: a -> a -> a
x .* y = {-something-}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.