Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 '(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))))
like image 609
Jason M. Avatar asked Dec 06 '25 15:12

Jason M.


1 Answers

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)
like image 151
Óscar López Avatar answered Dec 09 '25 06:12

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!