![](/img/trans.png)
[英]Why we cannot pattern match on Set/Type in Coq/Agda/Idris?
[英]How to map Type to Value in Idris/Agda/Coq?
我正在嘗試定義一個名為byteWidth
的函數,它捕獲有關“獲取特定原子類型的字節寬度”的用法。
我的第一次試用:
byteWidth : Type -> Int
byteWidth Int = 8
byteWidth Char = 1
並且Idris編譯器抱怨:“當檢查byteWidth的左側時:左側沒有顯式類型:Int”
我的第二次試驗:
interface BW a where
byteWidth : a -> Int
implementation BW Int where
byteWidth _ = 8
implementation BW Char where
byteWidth _ = 1
在這種情況下,我只能使用byteWidth
如byteWidth 'a'
但不能使用byteWidth Char
。
您的第二次嘗試非常接近原則解決方案。 正如您所觀察到的那樣,問題是在實現BW a
時不能將類型a
作為參數。 但是你並不在意,因為你總是可以在以后明確地設置隱式參數。
這給了我們:
interface BW a where
byteWidth_ : Int
implementation BW Int where
byteWidth_ = 8
implementation BW Char where
byteWidth_= 1
然后,您可以通過部分應用byteWidth_
來恢復所需的類型, byteWidth_
所示:
byteWidth : (a : Type) -> BW a => Int
byteWidth a = byteWidth_ {a}
在Idris中,你不能模式匹配一個類型,並且假設你可以,任何人都不可能枚舉所有可能的類型,所以它不能是完全的。
你需要的唯一額外的東西是關於類型a
在某個特定集合中的證明,我們將這個命題命名為ByteWidthAvailable
。
data ByteWidthAvailable : Type -> Type where
IntBWA : ByteWidthAvailable Int
ChaBWA : ByteWidthAvailable Char
total
byteWidth : (a : Type) -> {auto prf: ByteWidthAvailable a} -> Int
byteWidth _ {prf = IntBWA} = 8
byteWidth _ {prf = ChaBWA} = 1
這里唯一的技巧是由Idris提供的auto
命令,它有助於在調用站點自動生成證據,因此您可以調用byteWidth
如byteWidth Char
而不是byteWidth Char {prf = ChaBWA}
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.