1
votes

How to simulation "list? function" by define-struct.

I want to define struct to binary tree and check each mycons's right node is make-mycons or empty.

Only focus on check right node needed be mycons or empty.

(I already found list?'s sourece code from github but it beyond my ability.)

#lang racket
(define-struct mycons (left right) #:mutable #:transparent)

(define (mylist? l)
  (cond
    [(empty? l) #t]
    [(mycons? l) ...]
    [... ]))

(define correct (make-mycons (make-mycons 1 empty) (make-mycons 1 empty)))
(define wrong (make-mycons 3 (make-mycons 2 4)))

;;; expect
(equal? (mylist? empty) #t)
(equal? (mylist? correct) #t)
(equal? (mylist? wrong) #f)
1

1 Answers

0
votes

A simple version of list?:

(define (my-list? x)   
  (cond
    [(eq? x '()) #t]
    [(pair? x)   (my-list? (cdr x))]
    [else       #f])

The builtin list? is smarter though. When cons is called it checks whether the last argument is a list and if it is, flips a bit in the internal representation of the cons cell. This means that the builtin list? is O(1) rather than O(n) as the solution above.