Jas
Jas

Reputation: 15093

in clojure why isn't x identified if defined as [x] argument and then referenced as x? in code block?

(defn boolean [x]
  (if (x? nil or false)
    (false)
    (true)))

I get

Unable to resolve symbol: x? in this context

x is an argument to the function and I just reference it, what did I miss?

Upvotes: 0

Views: 65

Answers (3)

turingcomplete
turingcomplete

Reputation: 2188

Because x and x? are two different names. Your function could be simply written as

(defn boolean [x]
  (if x true false))

Upvotes: 3

Joost Diepenmaat
Joost Diepenmaat

Reputation: 17773

In clojure x? is the name of a symbol, not a symbol x and an operator ?. The compiler is telling you that you didn't define any variable or binding named x?.

In addition (false) and (true) call the boolean values as a function. That will throw a run time error. Use false and true instead.

Upvotes: 2

fl00r
fl00r

Reputation: 83680

I am not sure what is your problem (you didn't ever defined x?) but you could implement it in Clojure like this

(defn boolean [x]
  (not
    (or 
      (nil? x) 
      (false? x))))

(boolean 1)
#=> true
(boolean nil)
#=> false
(boolean false)
#=> false
(boolean [])
#=> true

Or more implicit solution

(defn boolean [x]
  (if x
    true
    false))

Or your approach:

(defn boolean [x]
  (if (or (nil? x) (false? x))
    false
    true))

Upvotes: 1

Related Questions