Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure unqoute problem

Tags:

syntax

clojure

i have a simple clojure syntax problem (bc i am new to the language). for both examples i have a list lst of (1 2 3 4):

in Lisp i can write:

=>`(first of list is ,(first lst))
(first of list is 1)

in Clojure, if i write the same thing (with the language translation of , to ~ as i THOUGHT i read somewhere) i get:

=>'(first of list is ~(first lst))
(first of list is (clojure.core/unquote (first lst)))

i was hoping i can do what i want to in Clojure as well, and that i just have the syntax wrong. all the examples i find though have functions first and use a ` (backtick). i dont want to call a function like:

`(my-function ~(first lst))

i just want to return '(some list with ,(first lst) replaced in it)

can i do such a thing in Clojure?

EDIT: i gave a poor example seeing as my ACTUAL problem dealt with strings. let me try another example...

=>(def color-lst '(red green blue))

what i wanted to return was:

=>`(the color i want is ~(first color-lst))

this yeilded all the strange returns i saw. the other way to do this is

=>(format "the color i want is %s" (first color-lst))

this is how i solved my problem.

like image 960
trh178 Avatar asked Feb 26 '23 15:02

trh178


1 Answers

Even if your problem is solved, there are some fundamental differences between CL and Clojure worth mentioning:

The main difference concerning symbols in backquotes between CL and Clojure is, that Clojure resolves quasiquoted symbols; yielding a namespace qualified symbol (take a look at the reader section of the Clojure docs):

user> `foo
user/foo

So, in CL:

CL-USER> (let ((list '(foo bar baz)))
            `(first is ,(first list)))
(FIRST IS FOO)

But in Clojure:

user> (let [lst '(foo bar baz)]
        `(first is ~(first lst)))
(clojure.core/first user/is foo)

In order to get a non-qualified symbol in Clojure (within backquotes), you'd have to use something like this:

user> `~'foo
foo

So, to get the same result as the CL version (ignoring readtable-case), you'd have to use:

user> (let [lst '(foo bar baz)]
        `(~'first ~'is ~(first lst)))
(first is foo)
like image 135
danlei Avatar answered Mar 08 '23 14:03

danlei