racket - Racket 中的 `hash?` 之类的检查是否支持鸭子类型?
问题描述
我是 Racket 新手的 Python 程序员...
我看过一些代码,例如:
(define table/c (and/c hash? (not/c immutable?)))
所以这意味着这个库中接受table/c
arg 的任何地方都应该是一个可变哈希表的对象。
我的问题是...... Racket 是否支持在这里进行鸭式打字(特别是为了满足合同hash?
)?
假设我想用 ak/v 存储支持的东西替换基本哈希表...是否有我可以实现的“哈希表”接口允许我的存储支持的自定义对象通过hash?
合同检查?
解决方案
我认为您真的想为此使用字典,但是如果您遇到需要hash?
进行合同检查的库,那么您可以使用模仿者。
这是我编写的一个函数,它尝试使用弱哈希,它有一个缓存,用于一些可能昂贵的计算,由(错误命名的)filler
函数表示,该函数将在丢失的键上调用。
我不太确定这类事情的语义(而且我不是这方面的专家),但它在实践中有效。
(define (make-cache filler)
(impersonate-hash
(make-weak-hash '())
(λ (ht key)
;; impersonate hash-ref by calling the filler
(unless (hash-has-key? ht key)
;; I think this is safe as the key won't be dropped
(hash-set! ht key (filler key)))
(values key (λ (ht k v) v)))
;; Everything else is passed through
(λ (ht k v)
(values k v))
(λ (ht k)
k)
(λ (ht k)
k)))
推荐阅读
- regex - 如何获得完全匹配忽略正则表达式中的非数字?
- apache-spark - 如何将火花日志转发到 jupyter 笔记本?
- python - Sympify Error when finding distance between 2 coordinates in pandas data frame
- node.js - express 和 socket.io 会话的问题
- android - 构建文件夹未在 android studio 项目中生成
- java - Visual Studio 代码 java 日期仅以毫秒返回
- comparison - 两个正态分布的比较
- flutter - 为什么我的应用程序颤动无法下载依赖项?
- python - 如何在 Python 3 中的多进程中启动非阻塞进程
- asp.net-mvc - MVC TTFB 太长