更新球拍中哈希表中的函数 [英] Update functions in Hash Table in Racket

查看:101
本文介绍了更新球拍中哈希表中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Racket的初学者,我正在尝试使用hash-update更新哈希表!该值是一个可变集合.下面是代码行:

I am a beginner in Racket and I am trying to updare a hash table using hash-update! where the value is a mutable set. Below are the code lines:

(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

where I tried 2 as the new_val

有什么建议吗?

推荐答案

这是因为更新程序应该是一个将值作为输入并产生新值输出的函数.由于该集合是可变的,因此您正在使用

This is because the updater is supposed to be a function that takes a value as input and produces a new value output. Since the set is mutable and you're using set-add! to mutate it, the "updater" isn't returning a new value, just mutating the old one and producing void.

有两种方法可以解决此问题:

There are two ways to fix this:

  1. 可变变量集作为值,分别对其进行突变,而不是在由于您已指定要让值作为可变集合,因此我将显示(1).

    Since you specified you want the values as mutable sets, I will show (1).

    您可以做的最基本的事情是

    The most basic thing you can do is hash-ref to get a mutable-set, and then use set-add! on that.

    (set-add! (hash-ref hash key) new-val)
    

    但是,当该键还没有可变设置值时,这将不起作用.如果尚不存在它,则需要将其添加到表中,这就是为什么要使用(mutable-set 1) failure-result参数的原因.解决方案不是

    However, this doesn't work when there is no mutable-set value for that key yet. It needs to be added to the table when it doesn't exist yet which why is why you have the (mutable-set 1) failure-result argument. The solution to this isn't hash-update!, it's hash-ref!.

    (set-add! (hash-ref! hash key (mutable-set 1)) new-val)
    

    尽管将失败结果包装在一个大块中可能会更好

    Although it would probably be better if you wrapped the failure-result in a thunk

    (set-add! (hash-ref! hash key (λ () (mutable-set 1))) new-val)
    

    这篇关于更新球拍中哈希表中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆