Skip to content

generic

Turtle Kitty edited this page Aug 10, 2015 · 3 revisions

gen

This operator creates a generic function with a default behavior that is executed if no spec predicate returns true. By default, generic functions are limited to an arity of 5; the programmer who needs higher arities can use the arity: option to pass a higher number.

spec

This operator creates a specific behavior for a generic function that is executed if its predicate returns true. The first expression after the argument list should be a predicate expression; subsequent expressions form the body of the spec.

(gen nosuke 'murakami arity: 7) ; default case

(spec nosuke (x) 
    x.pos?
    (* x x)) 

(spec nosuke (x) 
    x.neg?
    (- (* x x)))

(spec nosuke (x y)
    (> x y)
    (+ x y)) 

(spec nosuke (x y)
    (< x y)
    (- y x)) 

(spec nosuke (x y)
    (= x y)
    (* x y)) 

(spec nosuke (x y z)
    rest.size.zero?
    (+ x y z)) 

(spec nosuke (x y z p d q r)
    true
    ((send (list x y z p d q r) 'map) (_ _.to-text)))

(list
    (nosuke 0)
    (nosuke 2)
    (nosuke -2) 
    (nosuke 2 3)
    (nosuke 3 2)
    (nosuke 4 4)
    (nosuke 1 2 3)
    (nosuke 1 2 3 4 5 6 7)) 

-> (murakami 4 -4 1 5 16 6 ("1" "2" "3" "4" "5" "6" "7"))

Note: the order in which spec functions are defined is important. spec predicates are tested in descending order of arity; in the case of equivalent arities, those defined later have their predicates tested first.

Clone this wiki locally