Skip to content

generic

TurtleKitty edited this page May 11, 2019 · 2 revisions

gen

This operator creates a generic function with a default behavior that is executed if no defined spec signature matches the types of the supplied arguments.

spec

This operator creates a specific behavior for a generic function that is executed if its argument types match. The argument list differs from lambdas and procs in that each argument name is preceded by its type.

(gen weird
   (error 'argument-error
          %(weird @rest)
          "weird procedure not defined for the given argument types"))  ; default behavior: throw an error

(spec weird (lambda f int x)
   (+ (f x) 7))

(spec weird (lambda f number x)
   (+ (f x) math.pi))

(spec weird (number x vector v)
   (map (_ (* x _)) v))

(def square (L (x) (* x x)))
(def double (L (x) (+ x x)))

(weird square 5)              ; 32
(weird double 5)              ; 17
(weird square 2.3)            ; 8.43159265358979
(weird double 2.3)            ; 7.74159265358979
(weird 2 (vector 1 2 3))      ; #(vector 2 4 6)
(weird math.e (vector 1 2 3)) ; #(vector 2.71828182845905 5.43656365691809 8.15484548537714)
(weird 2 3)                   ; (runtime-error (argument-error (weird 2 3) "weird procedure not defined for the given argument types"))
Clone this wiki locally