tags:

views:

158

answers:

2

I'm learning clojure and have a very basic question: given that clojure has type infernece, how can you tell what class was inferred?

For instance, these would each result in difference data types:

(2)
(/ 2 3)
(/ 2.0 3)

Is there some kind of class function that will return the data type? Also, is there a normal way of casting something to be a specific type? So in the second example above, what would I do if I wanted it to be float?

+10  A: 

There is type function in clojure.core library.

user> (type 2)
java.lang.Integer

user> (type (/ 2 3))
clojure.lang.Ratio

user> (type (/ 2.0 3))
java.lang.Double
  • If you want to convert a given number into float then just use float function.

    user> (float 10)

    10.0

aatifh
Dang! `type` is not on the Clojure Cheat Sheet ( <http://clojure.org/cheatsheet> ) so I didn't find it :(
Carl Smotricz
There is also `class`. `type` basically checks the metadata (if any) first for the :type key. Then as fallback `class` is used.
kotarak
Very true! It also very useful.
aatifh
A: 

similarly you may not need to cast, because the following works:

user> (Double/toString (/ 2 3))
"0.6666666666666667
miaubiz