简体   繁体   中英

Racket: Graphing a parabola with elements from a list

I have created the following expression which I would like to graph parabolas based on the last two elements in a 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 a blank graph if true. The second conditional statement skips past numbers from the list which are less than or equal to 0. The third conditional statement checks if the length of the list is equal to 2, and goes down the list until the length is equal to 2. The else statement is where I get trouble when running an expression such as:

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

Which will result in an error reading:

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

From this error I am led to believe that the first element of the list is being read as a number, but that the second element is having trouble. Why is this?

Thank you in advance!

You are passing a list when plot ing. Remember cdr returns a list and not an element (like car does).

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

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