如何解决Idris中依赖类型函数的问题
我刚开始读一本书“类型驱动的开发”,并尝试了有关依赖类型的简单示例。它应该为负数返回一个字符串,为正数返回一个整数。 我从两个洞开始:
StringOrInt : Bool -> Type
StringOrInt b =
case b of
True => Integer
False => String
getStringOrInt : (x : Integer) -> StringOrInt (x > 0)
getStringOrInt x =
case x > 0 of
True => ?x
False => ?s
如果我看一下孔的定义,它看起来非常复杂,根本没有帮助:
x : case with block in Prelude.Interfaces.Prelude.Interfaces.Integer implementation of Prelude.Interfaces.Ord,method > (ifThenElse (intToBool (prim__eqBigInt x 0))
(Delay EQ)
(Delay (ifThenElse (intToBool (prim__sltBigInt x
0))
(Delay LT)
(Delay GT))))
x
0 of
True => Integer
False => String
那怎么写这个函数呢?
解决方法
使用with
而非case
来利用依赖的模式匹配,并让类型检查器在每种选择的结果类型中用x > 0
的适当布尔值代替:
StringOrInt : Bool -> Type
StringOrInt True = Integer
StringOrInt False = String
getStringOrInt : (x : Integer) -> StringOrInt (x > 0)
getStringOrInt x with (x > 0)
getStringOrInt x | True = x
getStringOrInt x | False = "<= 0"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。