Xodarap
Xodarap

Reputation: 11849

Function definitions in Clojure

I'm trying to use parse-ez, and I don't understand why I'm getting the results I am. When I define what seems to me to be equivalent code in a function, I get different results:

(use 'protoflex.parse)
;
; Use an anonymous function, this returns [1 1]
(parse #(line-pos) "")
;
; Use an actual function, this returns what I think is a function pointer
(defn fooParse [] line-pos)
(parse fooParse "")

What's the difference?

Upvotes: 1

Views: 113

Answers (2)

bdesham
bdesham

Reputation: 16089

To invoke a function in Clojure, you do

(my-function)

If, on the other hand, you say

my-function

this is just a reference to the function. (“Reference” isn’t a technical term here, but I think that makes it clear what I mean.) In your second example, the “return value” of the function fooParse is this second form of the function—it’s line-pos instead of (line-pos)—and so the thing being returned by fooParse is a reference to the function line-pos instead of the return value of line-pos. I think what you want is

(defn fooParse
  []
  (line-pos))

Upvotes: 2

Rodrigo Taboada
Rodrigo Taboada

Reputation: 2727

You have to call line-pos inside fooParse. Like this:

(defn fooParse [] (line-pos))

As you can see in the docs. The reader macro #() expands to:

#(...) => (fn [args] (...))

Upvotes: 3

Related Questions