justinsingh
justinsingh

Reputation: 33

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!

Upvotes: 3

Views: 123

Answers (1)

David Merinos
David Merinos

Reputation: 1295

You are passing a list when ploting. 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

Upvotes: 3

Related Questions