我正在通過Manning的Idris類型驅動開發。給出了一個例子,教導如何將函數限制在一個類型族中的給定類型。我們有Vehicle
類型,它使用PowerSource
,即Pedal
或Petrol
,我們需要編寫一個函數refill
,該類型只適用於使用汽油作爲能源的車輛。如何限制輸入類型和輸出類型相同?
以下代碼有效,但不能保證填充Car
將生成Car
而不是Bus
。我如何需要將refill
函數的簽名更改爲只允許在給出Car
時生成Car
並且在給出Bus
時生成Bus
?
data PowerSource
= Pedal
| Petrol
data Vehicle : PowerSource -> Type
where
Bicycle : Vehicle Pedal
Car : (fuel : Nat) -> Vehicle Petrol
Bus : (fuel : Nat) -> Vehicle Petrol
refuel : Vehicle Petrol -> Nat -> Vehicle Petrol
refuel (Car fuel) x = Car (fuel + x)
refuel (Bus fuel) x = Bus (fuel + x)
感謝這個答案!這種外部函數技巧的方法非常好! – Shersh