Page 1 of 1

How to implement function overwriting

Posted: Sat Jul 27, 2013 3:24 am
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?

Re: How to implement function overwriting

Posted: Sat Jul 27, 2013 12:25 pm
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)))))

Re: How to implement function overwriting

Posted: Sun Jul 28, 2013 1:41 am
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