Racket: Graphing a Parabola with List Items

I created the following expression that would like to draw parabolas based on the last two items in the list. It looks like this:

#lang racket
(require plot)

(define list-sqr-graph
  (lambda (lst)
    (cond
      [(null? lst) (plot (function sqr 0 0))]
      [(<= (car lst) 0) (list-sqr-graph (cdr lst))]
      [(not (equal? (length lst) 2)) (list-sqr-graph (cdr lst))]
      [else (plot (function sqr (car lst) (cdr lst)))])))

      

The first conditional statement checks if the list is null and returns an empty graph if true. The second conditional operator skips past numbers from the list that are less than or equal to 0. The third conditional operator checks if the length of the list is equal to 2 and goes down the list until the length is 2. The else statement is where I I get problems when executing an expression like:

(list-sqr-graph '(1 2 3))

      

This will result in an error:

function: contract violation
expected: (or/c rational? #f)
given: '(4)

      

From this error I am convinced that the first element of the list is being read as a number, but the second element has problems. Why is this?

Thank you in advance!

+3


source to share


1 answer


You pass the list when plot

ing. Remember cdr

returns a list, not an element (for example car

).

You want to use cadr

.



#lang racket
(require plot)

(define list-sqr-graph
  (lambda (lst)
    (cond
      [(null? lst) (plot (function sqr 0 0))]
      [(<= (car lst) 0) (list-sqr-graph (cdr lst))]
      [(not (equal? (length lst) 2)) (list-sqr-graph (cdr lst))]
      [else (plot (function sqr (car lst) (cadr lst)))]))) <- HERE

      

+3


source







All Articles