Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn (seq "foo") back into a string?

Tags:

clojure

I'm exploring clojure and am puzzled. What fills in the blank to make the following expression eval to true?

(= "foo" ___ (str (seq "foo")))
like image 385
mark Avatar asked May 04 '11 12:05

mark


3 Answers

You need to use apply function:

user=> (apply str (seq "foo"))
"foo"
like image 89
Alex Ott Avatar answered Nov 06 '22 22:11

Alex Ott


Actually nothing can fill in the blank to make the expression (= "foo" _ (str (seq "foo"))) eval to true because (str (seq "foo")) => "(\f \o \o)" which is not equal to "foo" so we have an inequality already and a third item, no matter what value, to fill the blank cannot make the expression evaluate to true

If you meant to ask

(= "foo"
    (____ str (seq "foo")))

Then the answer would rightly be apply as answered by alex.

user> (doc apply)
-------------------------
clojure.core/apply
([f args* argseq])
  Applies fn f to the argument list formed by prepending args to argseq.

Apply takes a function (in this case str) and calls str with the args present in the seq

user> (seq "foo")
(\f \o \o)

user> (str \f \o \o)
"foo"

And oh, btw:

user> (= 1 1 1)
true

user> (= 1 2 1)
false
like image 45
Jaskirat Avatar answered Nov 06 '22 22:11

Jaskirat


Or you could use the convient clojure.string/join

(require 'clojure.string)
(clojure.string/join (seq "foo"))

Will print "foo" as well. You could off course define your own join using the previously mentioned technique (to avoid write (apply str seq) all the time).

like image 4
isakkarlsson Avatar answered Nov 06 '22 22:11

isakkarlsson