如何解决使用内部自动类型定义 Nim 概念时遇到问题
我无法定义包含 auto
类型的概念。
Nim 似乎在抱怨 type T = auto
变成了 untyped
。
这是一个基本取自 run it online here) 的最小示例 (from the docs):
import sugar,typetraits
type
Functor[A] {.explain.} = concept f
type MatchedGenericType = genericHead(typeof(f))
# `f` will be a value of a type such as `Option[T]`
# `MatchedGenericType` will become the `Option` type
# f.val is A
# The Functor should provide a way to obtain
# a value stored inside it
type T = auto
map(f,A -> T) is MatchedGenericType[T]
# And it should provide a way to map one instance of
# the Functor to an instance of a different type,given
# a suitable `map` operation for the enclosed values
import options
echo Option[int] is Functor # should print true but doesn't!
# The above came straight from
# <https://nim-lang.org/docs/manual_experimental.html#concepts-generic-concepts-and-type-binding-rules>
proc f(x: Functor) = echo "yes!"
f(some(1))
这是错误的相关部分(除了文档说 Option[int] is Functor
应该是 true
但不是):
proc map[T,R](self: Option[T]; callback: proc (input: T): R): Option[R]
first type mismatch at position: 2
required type for callback: proc (input: T): R{.closure.}
but expression 'proc (i0: A): T' is of type: type proc (i0: int): untyped{.closure.}
我基本上是从文档中复制粘贴。我做错了什么?
解决方法
我不知道如何回答您关于在概念体中使用 auto
的问题,我的直觉是这不太可能奏效。
我可以通过删除自动内容以及使用 typedef 参数调用 map
来使您的示例工作吗?我也不明白。
import sugar,typetraits
type
Functor[A] {.explain.} = concept f,type t
type MatchedGenericType = genericHead(typeof(f))
# `f` will be a value of a type such as `Option[T]`
# `MatchedGenericType` will become the `Option` type
# f.val is A
# The Functor should provide a way to obtain
# a value stored inside it
#type T = auto
proc mapto[T](x:t):MatchedGenericType[T] = map(f,default(A->T))
#map(f,A->T) is MatchedGenericType[T]
# And it should provide a way to map one instance of
# the Functor to a instance of a different type,given
# a suitable `map` operation for the enclosed values
import options
echo Option[int] is Functor # prints true
# The above came straight from <https://nim-lang.org/docs/manual_experimental.html#concepts-generic-concepts-and-type-binding-rules>.
proc f(x: Functor) = echo "yes!"
f(some(1))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。