如何创建用于转换值的函数:x `as` T = y?
How can I create a function for casting values: x `as` T = y?
我有将某种类型的东西 this
转换为另一种类型 target
的接口。
interface ConvertibleTo (target : Type) (this : Type) where
convert : this -> target
我能否以某种方式编写一个函数,它采用 this
的某些值,然后是 target
类型,然后生成 target
类型的值?
我试过写这个
-- Example: 1 `as` String = "1"
as : ConvertibleTo target this => this -> (target : Type) -> target
as value _ = convert value
但它不起作用。编译器说
|
27 | as value _ = convert value
| ~~~~~~~~~~~~~
When checking right hand side of as with expected type
iType
Can't find implementation for ConvertibleTo iType this
我不理解该消息,因为我已经添加了约束。
问题是,(target : Type)
引入了一个内部称为 iType
的新变量(因为 target
已在别处分配),-> target
引用了它。因为约束使用 target
,所以它应该在这个参数之后。约束只是神奇的隐式参数,所以你不必把它们放在第一位:
interface ConvertibleTo (target : Type) (this : Type) where
convert : this -> target
as : this -> (target : Type) -> ConvertibleTo target this => target
as x _ = convert x
ConvertibleTo String Nat where
convert = show
> as (S Z) String
"1"
(如果您不知道,标准库中已经有一个 ConvertibleTo
接口,其中包含一些有用的实现:Cast from to
)
我有将某种类型的东西 this
转换为另一种类型 target
的接口。
interface ConvertibleTo (target : Type) (this : Type) where
convert : this -> target
我能否以某种方式编写一个函数,它采用 this
的某些值,然后是 target
类型,然后生成 target
类型的值?
我试过写这个
-- Example: 1 `as` String = "1"
as : ConvertibleTo target this => this -> (target : Type) -> target
as value _ = convert value
但它不起作用。编译器说
|
27 | as value _ = convert value
| ~~~~~~~~~~~~~
When checking right hand side of as with expected type
iType
Can't find implementation for ConvertibleTo iType this
我不理解该消息,因为我已经添加了约束。
问题是,(target : Type)
引入了一个内部称为 iType
的新变量(因为 target
已在别处分配),-> target
引用了它。因为约束使用 target
,所以它应该在这个参数之后。约束只是神奇的隐式参数,所以你不必把它们放在第一位:
interface ConvertibleTo (target : Type) (this : Type) where
convert : this -> target
as : this -> (target : Type) -> ConvertibleTo target this => target
as x _ = convert x
ConvertibleTo String Nat where
convert = show
> as (S Z) String
"1"
(如果您不知道,标准库中已经有一个 ConvertibleTo
接口,其中包含一些有用的实现:Cast from to
)