Referencing unbounded function in Clojure REPL - clojure

In the Common Lisp REPL I can do that:
>(DEFUN SOS (x y) (+ (sq x) (sq y)))
SOS
>(sos 5 4)
Error in SOS [or a callee]: The function SQ is undefined.
Fast links are on: do (use-fast-links nil) for debugging
Broken at +. Type :H for Help.
1 (Abort) Return to top level.
dbl:>>1
Top level.
>(DEFUN sq (x) (* x x))
SQ
>(sos 5 4)
41
>(quit)
If I try the same in Clojure the result is this:
user=> (defn sos [x y] (+ (sq x) (sq y)))
CompilerException java.lang.RuntimeException: Unable to resolve symbol: sq in this context, compiling:(NO_SOURCE_PATH:1:20)
user=> (quit)
Bye for now!
Why?

in clojure use declare to create forward references.
(declare sq)
(defn sos [x y] (+ (sq x) (sq y)))
This part of the one-pass compiler design decision.

Related

Null pointer exception when executing loop in clojure

(defn my-loop [x]
(cond (> x 1)
((println x)
(my-loop (- x 1)))
)
)
;; => #'user/my-loop
user> (my-loop 10)
Why do i get a null pointer exception, when executing this function?
Is this not a normal recursion?
You are invoking the return of (println x) with the additional layer of parentheses. println returns nil so invoking it will lead to the NullPointerException.
To evaluate more than one form where only one is expected use the do special form, which evaluates any number of forms and returns the value of the last one:
(defn my-loop [x]
(cond (> x 1) (do
(println x)
(my-loop (- x 1)))))
In this case, when can replace a one armed cond and do
(defn my-loop [x]
(when (> x 1)
(println x)
(my-loop (- x 1))))
The code should typically look something like so:
(defn my-loop
"Some docstring"
[x]
(cond
(> x 1) (println x)
:else (my-loop (- x 1))))
Keeping to good formatting helps to see problems early.
You may also be interested in this list of documentation sources, especially the Clojure CheatSheet & the book "Getting Clojure".

Clojure macros symbol evaluation

I'm confused with how symbols are evaluated inside the macro. I tried the following example
(defmacro fx-bad
[f x]
`(f x))
(defmacro fx
[f x]
`(~f ~x))
(let [f inc x 1] (fx f x)) ;-> 2
(let [f inc x 1] (fx-bad f x)) ;-> exception
fx macro functions correctly, whereas fx-bad throws the exception
CompilerException java.lang.RuntimeException: No such var: user/f, compiling:(/tmp/form-init2718774128764638076.clj:12:18)
Are the symbols resolving inside the macro? Why fx-bad doesn't work but fx does?
--
Edit:
Apparently the exception has something to do with namespaces. Actually no arguments are ever evaluated in the macro. ~ in the syntax quote just produces the actual string (Symbol) passed to macro, without it the symbol inside the list is returned as it is.
Interesting thing is is, if the arguments supplied to macro call and symbols inside the quoted (not syntax quoted) list have equivalent names, they doesn't have to be unquoted, they are the same symbol anyway. This is good indication, how macro takes place before the evaluation and just manipulates raw symbols which doesn't mean anything at this point.
However, with the syntax quote case is different, and exception is thrown until symbols are unquoted, even thought the expanded macro looks like a valid line of code for evaluator to evaluate. Here are some examples
(defmacro fx
[f x]
`(~f ~x))
(defmacro fx-bad
[f x]
'(f x))
(defmacro fx-very-bad
[f x]
`(f x))
`(let [f inc x 1] ~(macroexpand '(fx f x)))
`(let [f inc x 1] ~(macroexpand '(fx-bad f x)))
`(let [f inc x 1] ~(macroexpand '(fx-very-bad f x)))
(macroexpand '(fx (fn [a] a) b))
(macroexpand '(fx-bad (fn [a] a) b))
(macroexpand '(fx-very-bad (fn [a] a) b))
(let [f inc x 1] (fx f x)) ;-> 2
(let [ff inc xx 1] (fx ff xx)) ;-> 2
(let [f inc x 1] (fx-bad f x)) ;-> 2
;(let [ff inc xx 1] (fx-bad ff xx)) ;-> exception
;(let [f inc x 1] (fx-very-bad f x)) ;-> exception
--
=> #'user/fx
#'user/fx-bad
#'user/fx-very-bad
(clojure.core/let [user/f clojure.core/inc user/x 1] (f x))
(clojure.core/let [user/f clojure.core/inc user/x 1] (f x))
(clojure.core/let [user/f clojure.core/inc user/x 1] (user/f user/x))
((fn [a] a) b)
(f x)
(user/f user/x)
2
2
2
So what is actually happening here, why the exception is thrown in the case of syntax quote?
Please see full details in Clojure for the Brave & True and most other Clojure books.
Basically, the backquote creates a template, and the tilde tells the compiler which values to substitute. In Groovy, bash, & other languages, it is like substitution of variables in a string:
f = "+";
x = 1;
y = 2;
result = "(${f} ${x} y)"
result => "(+ 1 y)"
In this example, the y is not substituted. The Clojure macro equivalent would be:
(let [f '+
x 1
y 2]
`(~f ~x y) )
;=> (+ 1 y)
Since the y was not "unquoted" by a tilde, it is taken literally and is not replaced with the contents of the variable y.

Clojure eval with Math functions

I'm having problems eval-ing a LazySeq returned by Deriva:
(use 'clojure.core.matrix)
(use 'com.lambder.deriva.core)
(def f1 '(cos (* x y)))
(def f2 '(sin (* x y)))
(def f [f1 f2])
(def u ['x 'y])
(def x 4)
(def y 3)
(defn jacobian [f u]
(map #(partial-derivative f %) u)
)
Returns a LazySeq
((vector (* (* -1 (sin (* x y))) y) (* (cos (* x y)) y)) (vector (* (* -1 (sin (* x y))) x) (* (cos (* x y)) x)))
Which can be successfully eval-ed using the REPL:
(eval (into [] (jacobian f u)))
Results in the correct matrix
[[1.609718754001305 2.5315618761974763] [2.1462916720017398 3.3754158349299686]]
If I put the eval inside the clj file and lein run
(defn -main
[]
(eval (into [] (jacobian f u)))
)
I get Exception in thread "main" java.lang.RuntimeException: Unable to resolve symbol: sin in this context, compiling:(/tmp/form-init2786363415298022761.clj:1:113) since eval works in a different namespace.
Is there any way to include the clojure.math functions in the temporary namespace generated by eval? Or is there a better way to evaluate the expression?
Maybe you need to use java.lang.Math/sin function of java.
Consider using syntax-quote (`) instead quote (') to obtain fully qualified symbols that you can later eval:
's
=> s
`s
=> user/s
See more about quoting here:
https://blog.8thlight.com/colin-jones/2012/05/22/quoting-without-confusion.html

Clojure: How to count occurrences in a list?

I'm still pretty new to clojure, so I apologize if this a bit trivial. Basically, the issue is in the "then" part of the if statement: (if (symbol? (first slist)).
;counts the number of occurences of
(defn count-occurrences [s slist]
(if (empty? slist)
0
(if (symbol? (first slist))
(if (= (first slist) s)
(+ 1 (count-occurrences s (rest slist)))
(+ 0 (count-occurrences s (rest slist))))
(count-occurrences s (first slist))))) ;Problem on this line
(println (count-occurrences 'x '((f x) y (((x z) x)))))
To count elements in a nested list, you could try this function:
(defn count-occurrences [s slist]
(->> slist
flatten
(filter #{s})
count))
Test:
user> (count-occurrences 'x '((f x) y (((x z) x))))
;; => 3
user> (count-occurrences 'y '((f x) y (((x z) x))))
;; => 1
user> (count-occurrences 'z '((f x) y (((x z) x))))
;; => 1
As Diego Basch commented, the skeleton of your algorithm ought to be
(defn count-occurrences [s slist]
(+ (count-occurrencies s (first slist))
(count-occurrencies s (rest slist))))
... which has one or two little problems:
It never terminates.
It doesn't deal with a symbol.
It doesn't deal with an empty list.
slist might not be a list, and eventually, through first calls,
won't be.
How do we deal with these problems?
First, test whether were dealing with a symbol.
If we aren't, assume it's a list and test whether it's empty.
If not, apply the skeleton recursion.
... giving us something like this:
(defn count-occurrences [s x]
(if (symbol? x)
(if (= x s) 1 0)
(if (empty? x)
0
(+ (count-occurrences s (first x))
(count-occurrences s (rest x))))))
... which works:
(count-occurrences 'x '((f x) y (((x z) x))))
;3
This solution has several problems (which you'll come to appreciate) that make Mark's answer superior in practice. However, if you're trying to get to grips with recursion, this will do nicely.

Can clojure evaluate a chain of mixed arity functions and return a partial function if needed?

Suppose you have three functions of arity 1, 2 and 3 as below:
(defn I [x] x)
(defn K [x y] x)
(defn S [x y z] (x z (y z)))
Does clojure have an evaluation function or idiom for evaluating:
(I K S I I) as (I (K (S (I (I)))))
returning a parital function of arity 2?
I am considering creating a macro that can take the simple function definitions above and expand them to multi-arity functions that can return partial results. I would not want to create the macro if there is already a built in or idiomatic way to accomplish this.
Here is what the expanded macros would like for the above functions:
(defn I
([x] I x)
([x & more] (apply (I x) more)))
(defn K
([x] (partial K x))
([x y] x)
([x y & more] (apply (K x y) more)))
(defn S
([x] (partial S x))
([x y] (partial S x y))
([x y z] (x z (y z)))
([x y z & more] (apply (S x y z) more)))
I'm not sure I fully understand what you are trying to do, but the comp function is useful for doing this kind of "function chaining" you seem to be talking about. For example:
user> ((comp vec rest list) 1 2 3 4 5)
=> [2 3 4 5]
Which is equivalent to:
user> (vec (rest (list 1 2 3 4 5)))
=> [2 3 4 5]
In your case, if you have the list (I K S I I), and you want to evaluate it as (I (K (S (I (I))))), I would use (reduce comp ...), but you could also use (apply comp ...).
user> ((reduce comp [vec rest list]) 1 2 3 4 5)
=> [2 3 4 5]
user> ((apply comp [vec rest list]) 1 2 3 4 5)
=> [2 3 4 5]
You may also be interested in the -> or ->> macros. These macros nest their arguments sequentially into the next arguments. The -> macro will nest into the first position of the next expression, whereas the ->> macro will nest into the last position of the next expression. If the "next thing" is a function, both will behave the same, and form an expression of (function nested-things-so-far), and continue along.
Really, examples are best:
(-> 1 (+ 10) (- 100) inc)
;//Expands to...
(inc (- (+ 1 10) 100))
;//Evaluating in the REPL...
user> (-> 1 (+ 10) (- 100) inc)
=> -88
(->> 1 (+ 10) (- 100) inc)
;//Expands to...
(inc (- 100 (+ 10 1)))
;//Evaluating in the REPL...
user> (-> 1 (+ 10) (- 100) inc)
=> 90
However, it seems more like you want to do something involving auto-currying (although, again, I don't think I fully understand), and for that I don't know of anything pre-existing built-in way.