How to define such function

HI, I am a newbie to clojure. I am reading the guides of clojure at

  1. Define a function always-thing which takes any number of arguments, ignores all of them, and returns the keyword :thing.
(defn always-thing [__] ___)

taks any number of arguments:

(defn always-thing [& args] ___)

I don’t understand the keyword :thing means.

Keywords in Clojure are basically strings with a colon in front, so :thing just means literally typing the characters :thing. So to return the keyword :thing means letting :thing be the last expression in your function.

There is some caching going on behind the scenes, such that typing :thing multiple times only ever instantiates one keyword object, while creating multiple instances of the string "thing" would create multiple instances of String.

The Clojure documentation for keywords is a little on the brief side, but may be helpful anyway:

Keywords are often used interchangeably with strings. However unlike a string there is only ever one instance of a keyword, like there is only one instance of the number 1 etc. Therefore they are more memory efficient than strings. They are often used as the keys in a hash map, personally I prefer them visually to string keys.

{ :name "Apple" }
{ "name" "Apple" }

If you ever used Ruby it is the same as symbol in Ruby. Which caused me some confusion when I started learning Clojure, both have keywords and symbols but they aren’t the same thing.

I think the general idea is that a string should be used for text in your program to be consumed by the application users.

While if you need to name things for the computer or programmer to consume, then keywords are used.

In turn, the underlying implementation can be optimized towards the one use case or the other. Making Keyword more optimal for data structure keys for example, and string better for text.

And the solution is

(defn always-thing [& args] :thing)

I got it. Thank you all!


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.