Advertisement
Guest User

Untitled

a guest
Jun 11th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. (defstruct predicate-dispatch-method predicates function)
  2.  
  3. (defun find-predicate-dispatch-method (name parameters)
  4. (dolist (method (get name 'predicate-dispatch-methods))
  5. (when (every (function funcall)
  6. (predicate-dispatch-method-predicates method)
  7. parameters)
  8. (return-from find-predicate-dispatch-method (predicate-dispatch-method-function method))))
  9. (lambda (&rest arguments)
  10. (error "Cannot find a method to dispatch on the arguments ~S of the function ~S"
  11. arguments name)))
  12.  
  13. (defun set-predicate-dispatch-method (name predicates function)
  14. (push (make-predicate-dispatch-method :predicates predicates
  15. :function function)
  16. (get name 'predicate-dispatch-methods)))
  17.  
  18. (defmacro define-predicate-dispatch-function (name (&rest parameters))
  19. `(progn
  20. (setf (get ',name 'predicate-dispatch-methods) '())
  21. (defun ,name (,@parameters)
  22. (funcall (find-predicate-dispatch-method ',name (list ,@parameters)) ,@parameters))))
  23.  
  24. (defmacro define-predicate-dispatch-method (name (&rest parameters-and-predicates) &body body)
  25. `(set-predicate-dispatch-method ',name ',(mapcar (function second) parameters-and-predicates)
  26. (lambda (,@(mapcar (function first) parameters-and-predicates))
  27. (block ,name ,@body))))
  28.  
  29.  
  30. (define-predicate-dispatch-function foo (x y))
  31.  
  32. (define-predicate-dispatch-method foo ((x stringp) (y numberp))
  33. (foo (read-from-string x) y))
  34.  
  35. (define-predicate-dispatch-method foo ((x numberp) (y numberp))
  36. (+ x y))
  37.  
  38. (foo "33" 42)
  39. ; --> 75
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement