Oleg Kiselyov 展示了如何通过使用分隔的延续从任何可穿越的拉链制作拉链.他的Haskell代码非常简短:
module ZipperTraversable where
import qualified Data.Traversable as T
import qualified Data.Map as M
-- In the variant Z a k, a is the current, focused value
-- evaluate (k Nothing) to move forward
-- evaluate (k v) to replace the current value with v and move forward.
data Zipper t a = ZDone (t a)
| Z a (Maybe a -> Zipper t a)
make_zipper :: T.Traversable t => t a -> Zipper t …Run Code Online (Sandbox Code Playgroud) 在下面的代码中,我定义了一个通用链表。Go1.18 很乐意使用列表的实例作为映射的键。但是,最后一行如果未注释,则无法编译;我收到错误:
Cons[int] 没有实现可比较
是否有一个较弱的类型约束我可以使用来挑选出那些可以用作键的类型,或者这是有意的,还是它是一个编译器错误?
package main
import "fmt"
type List[X any] interface {
isList()
}
type Cons[X any] struct {
Data X
Next List[X]
}
func (Cons[X]) isList() {}
type Nil[X any] struct{}
func (Nil[X]) isList() {}
func id[X comparable](x X) X { return x }
func main() {
x := Cons[int]{5, Nil[int]{}}
m := map[List[int]]string{}
m[x] = "Hi" // succeeds
fmt.Println(m[x]) // prints "Hi"
// fmt.Println(id(x)) // fails
}
Run Code Online (Sandbox Code Playgroud)