Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. ; if slist is null, return empty
  2. ; otherwise, if it is a pair, recursively solve car and cdr and concat them
  3. ; if it is a symbol, return the symbol
  4.  
  5. (define flatten
  6. (lambda (slist)
  7. (cond
  8. [ (null? slist) '()]
  9. [ (pair? slist)
  10. (cons ((flatten (car slist)) (flatten (cdr slist))))]
  11. [ (symbol? slist) slist])))
  12.  
  13. procedure application: expected procedure, given: c; arguments were: ()
  14.  
  15. I did the trace:
  16. > (flatten '(a (b c) d))
  17. pair?-car-cdr
  18. a
  19. ((b c) d)
  20. symbol?
  21. a
  22. pair?-car-cdr
  23. (b c)
  24. (d)
  25. pair?-car-cdr
  26. b
  27. (c)
  28. symbol?
  29. b
  30. pair?-car-cdr
  31. c
  32. ()
  33. symbol?
  34. c
  35. (stops here)
  36.  
  37. (define flatten
  38. (lambda (slist)
  39. (cond
  40. [ (null? slist) '()]
  41. [ (pair? slist)
  42. (display 'pair?-car-cdr)
  43. (newline)
  44. (display (car slist))
  45. (newline)
  46. (display (cdr slist))
  47. (newline)
  48. (cons ((flatten (car slist)) (flatten (cdr slist))))]
  49. [ (symbol? slist)
  50. (display 'symbol?)
  51. (newline)
  52. (display slist)
  53. (newline)
  54. slist])))
  55.  
  56. (define flatten
  57. (lambda (slist)
  58. (cond
  59. [ (null? slist) '()]
  60. [ (pair? slist)
  61. (cons (flatten (car slist)) (flatten (cdr slist)))]
  62. [ (symbol? slist) slist])))
  63.  
  64. (display (equal? (flatten '(a (b a) b a c (a b) c (e f (b a)))) '(a b a b a c a b c e f b a)))
  65. (newline)
  66. (display (equal? (flatten '(a b c)) '(a b c)))
  67. (newline)
  68. (display (equal? (flatten '(a (b c))) '(a b c)))
  69. (newline)
  70. (display (equal? (flatten '((a)(b)(c) d)) '(a b c d)))
  71. (newline)
  72. (display (equal? (flatten '(a (b) ((c)) (((d))) ((((e (f g))))))) '(a b c d e f g )))
  73. (newline)
  74. (display (equal? (flatten '()) '()))
  75. (newline)
  76. (display (equal? (flatten '(a b () ())) '(a b)))
  77. (newline)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement