Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums and Clojure

Tags:

In the Java/C world, people often use enums. If I'm using a Java library which using enums, I can convert between them and keywords, for example, using (. java.lang.Enum valueOf e..., (aget ^"[Ljava.lang.Enum;" (. e (getEnumConstants)) i), and some reflection. But in the Clojure world, do people ever need anything like an enum (a named integer) ? If not, how is their code structured that they don't need them ? If yes, what's the equivalent ? I sense I'm really asking about indices (for looping), which are rarely used in functional programming (I've used map-indexed only once so far).

like image 405
Hendekagon Avatar asked Aug 08 '12 00:08

Hendekagon


People also ask

Why enums should not be used?

The problem with enums is described in Fowler's Refactoring, where it is considered a code smell. It has nothing to do with type safety, but rather that it forces you to sprinkle switch statements all over your code, thus violating the DRY Principle.

Are enums better than strings?

The advantage of an enum is that they are a strongly typed value. There are no advantages to using strings.

Are enums faster than strings?

Comparisons of enums usually are faster than comparisons of strings.

What is difference between enum and enumeration?

Enumeration is created by using a keyword called “enum”. Given below is the syntax with which we can create an enumeration. Note: enum can be defined only inside a top-level class or interface or in a static context. It should not be inside a method.


1 Answers

For almost all the Clojure code I have seen keywords tend to be used instead of Enums they are name-spaced and have all the other useful properties of keywords while being much easier to write. They are not an exact standin because they are more dynamic (as in dynamic typing) than Java enums

as for indexing and looping I find it more idiomatic to map over a sequence of keywords:

(map do-stuff [:a :b :c :d] (range))  

than to loop over the values in an enumeration, which I have yet to find an example of in Clojure code, though an example very likely exists ;-)

like image 148
Arthur Ulfeldt Avatar answered Sep 18 '22 06:09

Arthur Ulfeldt