在 Racket 中更新 Hash Table 中的函数
Update functions in Hash Table in Racket
我是 Racket 的初学者,我正在尝试使用哈希更新来更新哈希 table!其中值是一个 mutable 集合。以下是代码行:
(hash-update! hash key (curryr set-add! new_val) (mutable-set 1))
但是我收到一个错误
expected: set?
given: #<void>
argument position: 1st
other arguments...:
x: 2
我尝试将 2 作为 new_val
有什么建议吗?
这是因为更新器应该是一个将值作为输入并产生新值输出的函数。由于集合是 mutable 并且您正在使用 set-add!
对其进行变异,因此 "updater" 不会返回新值,只是变异旧值并产生 void.
有两种方法可以解决这个问题:
- Mutable 设置为值,分别对它们进行变异,而不是在
hash-update!
. 内部
- Immutable 设置为值,在
hash-update!
. 中使用功能更新程序
既然你指定你想要 mutable 集的值,我将显示 (1)。
你能做的最基本的事情是hash-ref
得到一个mutable-set,然后在上面使用set-add!
.
(set-add! (hash-ref hash key) new-val)
但是,当该键还没有 mutable-set 值时,这将不起作用。它需要在 table 尚不存在时添加到它,这就是为什么你有 (mutable-set 1)
失败结果参数的原因。解决方案不是 hash-update!
,而是 hash-ref!
.
(set-add! (hash-ref! hash key (mutable-set 1)) new-val)
尽管如果将失败结果包装在 thunk 中可能会更好
(set-add! (hash-ref! hash key (λ () (mutable-set 1))) new-val)
我是 Racket 的初学者,我正在尝试使用哈希更新来更新哈希 table!其中值是一个 mutable 集合。以下是代码行:
(hash-update! hash key (curryr set-add! new_val) (mutable-set 1))
但是我收到一个错误
expected: set?
given: #<void>
argument position: 1st
other arguments...:
x: 2
我尝试将 2 作为 new_val
有什么建议吗?
这是因为更新器应该是一个将值作为输入并产生新值输出的函数。由于集合是 mutable 并且您正在使用 set-add!
对其进行变异,因此 "updater" 不会返回新值,只是变异旧值并产生 void.
有两种方法可以解决这个问题:
- Mutable 设置为值,分别对它们进行变异,而不是在
hash-update!
. 内部
- Immutable 设置为值,在
hash-update!
. 中使用功能更新程序
既然你指定你想要 mutable 集的值,我将显示 (1)。
你能做的最基本的事情是hash-ref
得到一个mutable-set,然后在上面使用set-add!
.
(set-add! (hash-ref hash key) new-val)
但是,当该键还没有 mutable-set 值时,这将不起作用。它需要在 table 尚不存在时添加到它,这就是为什么你有 (mutable-set 1)
失败结果参数的原因。解决方案不是 hash-update!
,而是 hash-ref!
.
(set-add! (hash-ref! hash key (mutable-set 1)) new-val)
尽管如果将失败结果包装在 thunk 中可能会更好
(set-add! (hash-ref! hash key (λ () (mutable-set 1))) new-val)