Tornike Shavishvili
Tornike Shavishvili

Reputation: 1354

How Can i construct correct String in Clojure?

I am newbie in Clojure. I have following Expressions:

(= (__ "Dave") "Hello, Dave!")

(= (__ "Jenn") "Hello, Jenn!")

(= (__ "Rhea") "Hello, Rhea!")

In place of __, in all 3 places must be inserted same expression so that the equality check in all 3 cases are true. At this point i have come up with str "Hello, ". As i understand this should produce "Hello, Dave" "Hello, Jenn" "Hello, Rhea" How do i put "!" mark at the and of each string? (I can only "write" expression in place of __)

Thank you

Upvotes: 0

Views: 100

Answers (1)

David Tonhofer
David Tonhofer

Reputation: 15316

You want to drop a function into the place of __.

This function shall take a string s and shall return a string that is based on s so as to satisfy the three test cases.

A possible function is

(fn [s] (str "Hello, " s "!"))

which can written using Clojure syntactic sugar

#(str "Hello, " % "!"))

Thus

(= (#(str "Hello, " % "!") "Dave") "Hello, Dave!")

Bonus: Using testing framework

Clojure comes with a nice testing library, clojure.test (I don't know why it is called an API, which would mean there is a component on the other side of the callable functions; it's just a library)

We can use the testing library for good effect:

(require '[clojure.test :as t]) ; make library visible

(def myfun (fn [s] (str "Hello, " s "!"))) ; our function as symbol myfun

(t/deftest test-stringmanip
   (t/is (= (myfun "Dave") "Hello, Dave!"))
   (t/is (= (myfun "Jenn") "Hello, Jenn!"))
   (t/is (= (myfun "Rhea") "Hello, Rhea!")))

(t/run-tests) ; do it!

Upvotes: 5

Related Questions