簡體   English   中英

如何在Idris / Agda / Coq中映射Type到Value?

[英]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

在這種情況下,我只能使用byteWidthbyteWidth '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命令,它有助於在調用站點自動生成證據,因此您可以調用byteWidthbyteWidth Char而不是byteWidth Char {prf = ChaBWA}

暫無
暫無

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

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