How to implement function overwriting

Started by csfreebird, July 26, 2013, 08:24:29 PM

Previous topic - Next topic

csfreebird

I want to make one function support different argument combinations

like that in API:

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

#1
You define your functions without arguments, like this:



(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:



(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

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



;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