使用方案/球拍从列表中返回特定项目 [英] Using scheme/racket to return specific items from a list

查看:91
本文介绍了使用方案/球拍从列表中返回特定项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是创建一个函数,该函数接受一个值列表和一个字符列表,并将相应的字符(原子",我认为它们在技术上称为原子")合并为一个新列表.

What I would like to do is create a function that takes in a list of values and a list of characters and coalesce the corresponding characters("atoms" I think they would technically be called) into a new list.

这是我到目前为止所拥有的;

Here is what I have so far;

#lang racket
(define (find num char)
  (if (= num 1) 
     (car char)                                    ;Problem here perhaps?
     (find (- num 1) (cdr char))))


(define (test num char)
  (if (null? num)
    '("Done")
    (list (find (car num) (test (cdr num) char)))))

但是,这给了我一个错误,在大多数情况下,我理解它在说什么,但我看不出是什么错误导致了该错误.给出以下简单的测试输入,这就是我得到的

This however gives me an error, which for the most part I understand what it is saying but I don't see what is wrong to create the error. Given the following simple test input, this is what I get

> (test '(2 1) '(a b c))

car: contract violation
expected: pair?
given: '()

基本上,输出应该是'(b a)而不是明显的错误.

Essentially the output should be '(b a) instead of the error obviously.

不妨为新的方案用户提供一些帮助和指导!

A little help and guidance for a new scheme user would be appreciated!

这是我能够运行的代码.

Here is the code that I was able to get running.

#lang racket

(define (find num char)
  (cond ((empty? char) #f)
    ((= num 1) (car char))
    (else (find (- num 1) (cdr char)))))


(define (project num char)
  (if (empty? num)
    '()
    (cons (find (car num) char) (project (cdr num) char))))

推荐答案

find过程基本上是正确的(尽管它基本上是在重新发明轮子,并且做与list-ref一样的事情,但是...)小心,并且不要忘记考虑列表为空的情况:

The find procedure is mostly right (although it's basically reinventing the wheel and doing the same that list-ref does, but well...) just be careful, and don't forget to consider the case when the list is empty:

(define (find num char)
  (cond ((empty? char) #f)
        ((= num 1) (car char))
        (else (find (- num 1) (cdr char)))))

另一方面,project过程并不完全正确.您现在应该知道如何编写用于遍历列表并创建新列表作为答案的配方.我会给您一些提示,并填写空白:

The project procedure, on the other hand, is not quite right. You should know by now how to write the recipe for iterating over a list and creating a new list as an answer. I'll give you some tips, fill-in the blanks:

(define (project num char)
  (if <???>                    ; if num is empty
      <???>                    ; then we're done, return the empty list
      (cons                    ; otherwise cons
       <???>                   ; the desired value, hint: use find
       (project <???> char)))) ; and advance the recursion

这应该可以解决问题:

(test '(2 1) '(a b c))
=> '(b a)

这篇关于使用方案/球拍从列表中返回特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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