List 从球拍高级学员中另一个列表的位置编号制作列表
我目前正在尝试编写一个函数,该函数为我提供一个列表,其中包含元素1作为元素的位置的位置号 不幸的是,当我执行下面的函数时,它给出了List 从球拍高级学员中另一个列表的位置编号制作列表,list,scheme,racket,List,Scheme,Racket,我目前正在尝试编写一个函数,该函数为我提供一个列表,其中包含元素1作为元素的位置的位置号 不幸的是,当我执行下面的函数时,它给出了'(),这是lst的初始值 所以我不知道该为这个案例写些什么(
'()
,这是lst
的初始值
所以我不知道该为这个案例写些什么(
(定义lst'())
(定义(位置J位置)(如果(<0位置)
lst
(开始(第二个)(相等)(列表参考位置)1)(开始(设置!第一个(附加(列表*位置)'))
(posj(-pos1)))
(其他(职位-1(()()())))
(定义l'(1 3 1 2 1 5 1))
(位置J(-(长度l)1))
您的代码不起作用(只添加列表),并且由于多种原因无法在Scheme中执行
我建议使用(经典方案):
或者更“吵闹”
然后
由于您使用的是Racket和Dr Racket(IDE)
你可能想写的是这样的,用
list
代替list*
,lst
代替,()
:(还有更标准的缩进)
到目前为止,l
每次都是相同的列表,而您实际需要的零件每次都会缩小。要解决这个问题,您可以从前面到后面而不是从后面进行迭代,并在递归中使用first
和rest
。另外,append
的参数顺序也必须切换,因为我们现在正在另一个方向迭代,(
检查可以替换为(空?l)
检查:
(define (posj l lst pos)
(if (empty? l)
lst
(cond [(equal? (first l) 1)
(posj (rest l) (append lst (list pos)) (+ pos 1))]
[else
(posj (rest l) lst (+ pos 1))])))
(define l '(1 3 1 2 1 5 1))
(posj l '() 0)
现在,如果您可以使用cons
,而不是使用append
,效率会更高。这会反转lst
,因此将其重命名为rev lst
,当您返回它时,再次反转它:
(define (posj l rev-lst pos)
(if (empty? l)
(reverse rev-lst)
(cond [(equal? (first l) 1)
(posj (rest l) (cons pos rev-lst) (+ pos 1))]
[else
(posj (rest l) rev-lst (+ pos 1))])))
(define l '(1 3 1 2 1 5 1))
(posj l '() 0)
现在,它开始看起来很像列表函数的模板,特别是如果您将
if
替换为cond
。另外,如果您想避免将'()
和0
作为额外参数传递,您可以使用helper函数或命名let。您可以显示示例用法和期望值吗?如果我将“(1 3 1 2 1 5 1)作为列表,我希望它返回我”(0 2 4 6),其中元素的位置在(1 3 1 2 1 5 1)。我希望这是清楚的。我们在学校做过Scheme,但让我困惑的是我们将语言改为Racket时的限制。例如,一些内置函数非常有用,但在Advanced Student中没有定义。有时我没有发现发生的错误,我到处搜索,找不到解决方案。例如,我写了函数中的一个letrec,它给了我以下错误:“letrec:需要绑定变量,但找到了一个部分”因为我尝试定义和lambda的第一个变量有一个函数,但没有起作用:/如果需要解释,请打开另一个问题。但是你是对的,教学语言有时有奇怪的限制。非常感谢!现在我可以清楚地看到我的错误在哪里了
(define (posj lst val)
(reverse
(for/fold ((res null)) (((elt pos) (in-indexed lst)))
(if (= elt val) (cons pos res) res))))
> (posj '(1 3 1 2 1 5 1) 1)
'(0 2 4 6)
(define lst '())
(define (posj pos)
(if (< pos 0)
lst
(cond [(equal? (list-ref l pos) 1)
(begin
(set! lst (append (list pos) lst))
(posj (- pos 1)))]
[else
(posj (- pos 1))])))
(define l '(1 3 1 2 1 5 1))
(posj (- (length l) 1))
(define (posj l lst pos)
(if (< pos 0)
lst
(cond [(equal? (list-ref l pos) 1)
(posj l (append (list pos) lst) (- pos 1))]
[else
(posj l lst (- pos 1))])))
(define l '(1 3 1 2 1 5 1))
(posj l '() (- (length l) 1))
(define (posj l lst pos)
(if (empty? l)
lst
(cond [(equal? (first l) 1)
(posj (rest l) (append lst (list pos)) (+ pos 1))]
[else
(posj (rest l) lst (+ pos 1))])))
(define l '(1 3 1 2 1 5 1))
(posj l '() 0)
(define (posj l rev-lst pos)
(if (empty? l)
(reverse rev-lst)
(cond [(equal? (first l) 1)
(posj (rest l) (cons pos rev-lst) (+ pos 1))]
[else
(posj (rest l) rev-lst (+ pos 1))])))
(define l '(1 3 1 2 1 5 1))
(posj l '() 0)