How to implement function overwriting

Q&A's, tips, howto's
Locked
csfreebird
Posts: 107
Joined: Tue Jan 15, 2013 11:54 am
Location: China, Beijing
Contact:

How to implement function overwriting

Post by csfreebird »

I want to make one function support different argument combinations
like that in API:

Code: Select all

append

syntax: (append list-1 [list-2 ... ])
syntax: (append array-1 [array-2 ... ])
syntax: (append str-1 [str-2 ... ])
How to write my own function like that. Any document for this?

conan
Posts: 52
Joined: Sat Oct 22, 2011 12:14 pm

Re: How to implement function overwriting

Post by conan »

You define your functions without arguments, like this:

Code: Select all

(define (foo) (println $args)) ; -> (lambda () (println $args))
(foo 1 2 3) ; -> (1 2 3)
I put $args, but you can also use functions args or doargs. Check the manual for them, there're nice examples.

You may want to test the arguments' type to decide which signature should you act upon, there is a type function I found on this forum, but I don't recall where or who wrote it, so I'll paste it here:

Code: Select all

(define (type x)                                                                                                                                                         
    (let (types '(
        "bool" "bool" "integer" "float" "string" "symbol" "context" "primitive"
        "import-simple" "import-libffi" "quote" "list" "lambda" "macro" "array"))

        (types (& 0xf ((dump x) 1)))))

jopython
Posts: 123
Joined: Tue Sep 14, 2010 3:08 pm

Re: How to implement function overwriting

Post by jopython »

Are you referring to arity overloading like we have in clojure.

Code: Select all

;trumped-up example
(defn argcount
  ([] 0)
  ([x] 1)
  ([x y] 2)
  ([x y & more] (+ (argcount x y) (count more))))
-> #'user/argcount
(argcount)
-> 0
(argcount 1)
-> 1
(argcount 1 2)
-> 2
(argcount 1 2 3 4 5)
-> 5

Locked