PasteRack.org
Paste # 94316
2015-06-16 18:46:05

Fork as a new paste.

Paste viewed 689 times.


Embed:

Two macro (almost) replacements of ormap

  1. #lang racket
  2.  
  3. ;We compare two macros that act almost like ormap.
  4. ;The difference is that thefirst has an intermediate variable,
  5. ;so the proc definition is run only once.
  6. ;Anyway, both macros have an incorrect behavior
  7. ;when the items in the list have side effects.
  8.  
  9.  
  10.  
  11. (define-syntax m:ormap
  12.   (syntax-rules (list)
  13.     [(m:ormap proc (list n ...)) (let ([proc-val proc])
  14.                                    (or (proc-val n) ...))]))
  15. (define-syntax m:ormap/bad
  16.   (syntax-rules (list)
  17.     [(m:ormap proc (list n ...)) (or (proc n) ...)]))
  18.  
  19. ;Side effect in the procedure definition
  20. (ormap (begin (display "*") {lambda (x) (display x) #f}) (list 1 2 3))
  21. (m:ormap (begin (display "*") {lambda (x) (display x) #f}) (list 1 2 3))
  22. (m:ormap/bad (begin (display "*") {lambda (x) (display x) #f}) (list 1 2 3))
  23. (newline)
  24.  
  25. ;A different closure in each iteration
  26. (ormap (let ([r (random 6)]) {lambda (x) (display r) #f}) (list 1 2 3))
  27. (m:ormap (let ([r (random 6)]) {lambda (x) (display r) #f}) (list 1 2 3))
  28. (m:ormap/bad (let ([r (random 6)]) {lambda (x) (display r) #f}) (list 1 2 3))
  29. (newline)
  30.  
  31. ;Side effect in the list items
  32. (ormap {lambda (x) (display x) #f} (list 1 (begin (display "*") 2) 3))
  33. (m:ormap {lambda (x) (display x) #f} (list 1 (begin (display "*") 2) 3))
  34. (m:ormap/bad {lambda (x) (display x) #f} (list 1 (begin (display "*") 2) 3))
  35. (newline)

=>

*123

#f

*123

#f

*1*2*3

#f

555

#f

444

#f

155

#f

*123

#f

1*23

#f

1*23

#f