我正在通过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