简体   繁体   中英

Using scheme/racket to return specific items from a list

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: '()

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

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

EDIT:

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))))

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)))))

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

That should do the trick:

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

Better late than never:

(define (coalesce nums chars)
  (map (lambda (num) (list-ref chars (- num 1))) nums))

With higher order functions

#lang racket

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

(define (project nums chars)
 (let ((do-it (lambda (num) (find num chars))))
  (map do-it nums)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM