S.H.
S.H.

Reputation: 211

clojure - avoid extra whitespace when combining string and variable

I'm writing a program that uses printl-str to return commands of an assembly language. I need to use variables in my code and I'm having this issue where the function will return extra whitespace where I don't want it:

(defn pushConstant [constant]
   (println-str "@" constant "\r\nD=A\r\n@SP\r\nA=M\r\nM=D\r\n@SP\r\nM=M+1"))

Where instead of having, assuming that constant = 17

@17
D=A
@SP
A=M
M=D
@SP
M=M+1

I'm having:

@ 17
D=A
@SP
A=M
M=D
@SP
M=M+1

Which is problematic for my assembly code. I have this issue in so many cases like this. I'll be glad to hear advice on how to avoid this extra whitespace between the String and the variable.

Upvotes: 0

Views: 942

Answers (2)

Alex Miller
Alex Miller

Reputation: 70241

Create the string using str which only concatenates (println interleaves spaces):

(defn pushConstant [constant]
   (println-str (str "@" constant "\r\nD=A\r\n@SP\r\nA=M\r\nM=D\r\n@SP\r\nM=M+1")))

Upvotes: 3

Charles Duffy
Charles Duffy

Reputation: 295639

Frankly, I'd implement that to look more like the following:

(defn pushConstant [constant]
  (->> [(str "@" constant)
        "D=A"
        "@SP"
        "A=M"
        "M=D"
        "@SP"
        "M=M+1"]
       (interpose "\r\n")
       (apply str)))

That way you don't have one big ugly format string, but break down your operations into small, readable pieces.

That said, the piece that makes a difference for you here is (str "@" constant), combining your @ with the argument with no added whitespace.

Upvotes: 4

Related Questions