方案 - 用其索引替换列表中的元素 [英] Scheme - Replacing elements in a list with its index

查看:31
本文介绍了方案 - 用其索引替换列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用它的位置替换方案列表中的元素.例如,调用:

I am trying to replace the elements in a scheme list with its position. For example, calling:

(position '((a b) c))

应该返回:

'((0 1) 2)

到目前为止,我的代码保持列表格式,但索引没有更新.

So far, my code keeps the list format, but the index is not updating.

(define (position term1)
  (define index 0)
    (cond [(null? term1) '()]
          [(list? term1) (cons (position (car term1)) (position(cdr term1)))]
          [else (+ 1 index) index]))

(position '((a b) c))被调用时,返回

'((0 0) 0)

谁能解释为什么索引没有更新?

Can anybody explain why the index isn't updating?

推荐答案

有几个错误:首先要注意,每次递归调用 position 时,index 都绑定为零.

There are a couple things wrong: first notice that every time you recursively call position, index is bound to zero.

其次,看看你的 else 分支.(+ 1 index) 计算结果为 1(它不会改变任何变量)并且 index 计算结果为 0.这个分支只能计算一件事,所以发生的是最后一个被返回,其余的被丢弃.这就是您的零的来源.

Second, look at your else branch. (+ 1 index) evaluates to 1 (it does not change any variables) and index evaluates to 0. This branch can only evaluate to one thing, so what happens is the last one is returned and the rest are discarded. This is where your zeroes come from.

在您的函数中,您似乎试图保持全局状态(当前索引)并在每次标记叶子时对其进行修改.修改状态"部分不是很好的功能风格,但如果你同意,那么看看 设置!.

It seems like within your function you are trying to keep a global state (the current index) and modify it each time you label a leaf. The "modifying state" part is not good functional style, but if you are okay with that then take a look at set!.

这篇关于方案 - 用其索引替换列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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