BufBills
BufBills

Reputation: 8113

in clojure, function argument type mismatch

clojure, function argument is vector, but it takes a map without problem.

(defn flower-colors [colors]
  (str "The flowers are "
       (:flower1 colors)
       " and "
       (:flower2 colors)))

(flower-colors {:flower1 "red" :flower2 "blue"})
;; -> "The flowers are red and blue"

Function flower-colors suppose to take vector type argument, but with a map as input, it is still fine. Why?

Upvotes: 0

Views: 302

Answers (1)

Alan Thompson
Alan Thompson

Reputation: 29984

You are misunderstanding the format of a function definition.

In your function, the single argument 'colors' is untyped and can be anything. The square brackets are used to denote the beginning and end of the arguments list (i.e. the symbols for the arguments are wrapped in a vector to distinguish them from the following code expressions). So this function:

(defn foo [arg-1 arg-2] 
  { :first arg-1  :second arg-2 } )

(println (foo 1 2))
;=> {:first 1, :second 2}     ; return value

accepts 2 args and returns them in a simple map.

Without the square brackets, some other way of marking the first & last arguments would be required.

Upvotes: 4

Related Questions