Guest User

Untitled

a guest
Jun 19th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scheme 1.46 KB | None | 0 0
  1. #lang racket
  2.  
  3. ;; Defining a new structure, ilist, as a datatype to
  4. ;; store linked-list data.
  5. (define-struct ilist (head tail) #:mutable #:transparent)
  6.  
  7. ;; Defines an end-of-ilist condition
  8. ;; Runs in constant time O(1)
  9. (define iempty null)
  10.  
  11. ;; Predicate to test for the end-of-ilist condition
  12. ;; Runs in constant time O(1)
  13. (define iempty? (lambda (x) (if (equal? x iempty) #t #f)))
  14.  
  15. ;; Creates an ilist with first element(head) is ANY and
  16. ;; second element(tail) is another ilist.
  17. ;; Runs in constant time O(1)
  18. (define icons (lambda (x y) (make-ilist x y)))
  19.  
  20. ;; Returns the head of a consumed ilist.
  21. ;; Runs in constant time O(1)
  22. (define ifirst (lambda (x) (ilist-head x)))
  23.  
  24. ;; Returns the tail of the consumed ilist.
  25. ;; Runs in constant time O(1)
  26. (define irest (lambda (x) (ilist-tail x)))
  27.  
  28. ;; Returns the length of a given ilist, ie how many
  29. ;; "nested" ilist structures exist before the
  30. ;; end-of-list condition is met.
  31. ;; Runs in log(n) time O(log(n)) where n = number of
  32. ;; elements (heads before end) in ilist.
  33. (define (ilength ilist)
  34.   (if (iempty? ilist) 0
  35.       (+ 1 (ilength (irest ilist)))))
  36.  
  37. ;; Consumes to ilists and concatenates the first onto
  38. ;; the second. iappend is recursive and runs in log(n).
  39. (define iappend (lambda (x y) (if (iempty? x) y
  40.                                   (icons (ifirst x) (iappend (irest x) y)))))
  41.  
  42. (define tester (icons 1 (icons 2 (icons 3 iempty))))
  43.  
  44. (define tester2 (icons 4 (icons 5 (icons 6 iempty))))
Add Comment
Please, Sign In to add comment