Using scheme/racket to return specific items from a list

[亡魂溺海] 提交于 2020-01-04 02:30:48

问题


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 '(b a) 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))))

回答1:


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)



回答2:


Better late than never:

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



回答3:


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


来源:https://stackoverflow.com/questions/17312128/using-scheme-racket-to-return-specific-items-from-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!