Advertisement
Sax

hw05 - TC2006

Sax
Aug 29th, 2018
663
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Racket 1.64 KB | None | 0 0
  1. #lang racket
  2.  
  3. ; reversing a list
  4. (define (my_reverse x)
  5.     (if (null? x)
  6.         x
  7.         #| append rest of the elements (cdr) of my_reverse x
  8.         to the first part of x (car)
  9.         |#
  10.         (append (my_reverse (cdr x)) (list (car x)))
  11.     )
  12. )
  13.  
  14. ; Fibonacci digits
  15. (define (Fib x)
  16.     (cond
  17.       ((zero? x ) 0)
  18.       ((= x 1) 1)
  19.       (else
  20.         (+ (Fib (- x 1)) (Fib (- x 2)))
  21.       )
  22.     )
  23. )
  24.  
  25. ; sum ignoring lists
  26. (define (sum x)
  27.   (cond
  28.     ((null? x) 0)
  29.     ((= (length x) 1)
  30.       (if (number? (car x))
  31.         (car x)
  32.         0
  33.       )
  34.     )
  35.     (else
  36.       (if (number? (car x))
  37.         (+ (car x) (sum (cdr x)))
  38.         (sum (cdr x))
  39.       )
  40.     )
  41.   )
  42. )
  43.  
  44. ; nested sum
  45. (define (nested_sum x)
  46.   (cond
  47.     ((null? x) 0)
  48.     (else
  49.       (if (number? (car x))
  50.         (+ (car x) (nested_sum (cdr x)))
  51.         (+ (nested_sum (car x)) (nested_sum (cdr x)))
  52.       )
  53.     )
  54.   )
  55. )
  56.  
  57. ; remove nested lists
  58. (define (rmv_lists x)
  59.   (cond
  60.     ((null? x) x)
  61.     (else
  62.       (if (not (list? (car x)))
  63.         (append (list (car x)) (rmv_lists (cdr x)))
  64.         (append (rmv_lists (car x)) (rmv_lists (cdr x)))
  65.       )
  66.     )
  67.   )
  68. )
  69.  
  70. ; mean of a list of numbers
  71. ; we assume all elements of the input list are numbers
  72. ; we also assume there's no nested lists
  73. ; we use the previously defined sum function
  74.  
  75. (define (my_mean x)
  76.   (cond
  77.    ((null? x) (display "Error"))
  78.    (else
  79.     (/ (sum x) (length x))
  80.    )
  81.   )
  82. )
  83.  
  84.  
  85.  
  86. ;Test cases
  87. ;(my_reverse '(1 2 3 4 5 6))
  88. ;(Fib 8)
  89. ;(sum '('(1) 2 3 4 5))
  90. ;(nested_sum '(1 (2 (3)) (4 (5)) 6))
  91. ;(rmv_lists '(1 (((a 2) b) 3) c))
  92. ;(my_mean '(18 5.1 7 19.6 20))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement