macro-exercises-two.scm 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. (both-times
  2. '(def (nif-expand args)
  3. (=>> (.chop args 2)
  4. (map (lambda (x) (if (= (length x) 2) x (cons 'else x))))))
  5. (def (nif-expand args #!optional stx)
  6. (if-let-list ((test then . args*) args)
  7. (cons (list test then) (nif-expand args* stx))
  8. (if-let-list ((els) args)
  9. (list (list 'else els))
  10. (raise-source-error stx "missing else branch")))))
  11. (TEST
  12. > (nif-expand '(a "yes" b "no" "none"))
  13. ((a "yes") (b "no") (else "none"))
  14. > (%try-error (nif-expand '(a "yes" b "no")))
  15. [source-error "missing else branch"])
  16. (defmacro (nif . args)
  17. (cons 'cond (nif-expand args stx)))
  18. (defmacro (nif . args)
  19. (cons 'cond
  20. (let nif-expand ((args args))
  21. (if-let-list ((test then . args*) args)
  22. (cons (list test then) (nif-expand args*))
  23. (if-let-list ((els) args)
  24. (list (list 'else els))
  25. (raise-source-error stx "missing else branch"))))))
  26. (TEST
  27. > (expansion#nif a "yes" b "no" "none")
  28. (cond (a "yes") (b "no") (else "none")))
  29. ;;(def (m a b) (* a b))
  30. ;;(begin (step) (+ 10 (m 20 2)))
  31. (TEST
  32. > (def (t a b c)
  33. (nif a "a" b "b" c "c" "none"))
  34. > (t #f #f #f)
  35. "none"
  36. > (t #f #f #t)
  37. "c"
  38. > (t #t #f #t)
  39. "a"
  40. > (t #t #t #t)
  41. "a"
  42. > (t #f #t #t)
  43. "b")
  44. '(def (t2 a b c)
  45. (nif a "a" b "b" c "c"))