Clojure: Integer value ending with "N" - clojure

I have read about (*') function in clojure.
(*' 1234567890 9876543210)
Result: ;;=> 12193263111263526900N
I tried to execute this below
(*' 4535353535345345345 5675675675675675677 4564564646456645)
Result: ;;=> 117497352037570255927282105564555048448707485315089425N
What is "N" here? Is it symbol for Infinite? and the output is which type Bigdecimal or any other type?

(class (*' 4535353535345345345 5675675675675675677 4564564646456645))
is clojure.lang.BigInt and Clojure prints it like this:
;; src/clj/clojure/core_print.clj
(defmethod print-method clojure.lang.BigInt [b, ^Writer w]
(.write w (str b))
(.write w "N"))
so the N is just a note to let you know what type of integer it realy is.
This does not mean, though, you have to put N in the end to let Clojure know what kind of integer it is.

Related

Clojure: Name of variables in a list

I have a something like this:
(def a "text")
(def b "text")
(def c nil)
(def d 8)
(def e "")
(def testlist (list a b c d e ))
Now, is there any way to get the string of the variable names? I assume a 'no' is the most likely answer.
name does not seem to work, as it only returns the value. Does the list only contain the values after def?
EDIT: What i forgot and that may be essential to this question: i can neither use eval nor can i use defmacro, both are not allowed (for safety etc. reasons). So, yeah...
you could use macro to do this (just for fun. i don't think it is a viable usecase at all)
user> (defmacro list+ [& syms]
`(with-meta (list ~#syms) {:vars (quote ~syms)}))
#'user/list+
user> (def testlist (list+ a b c d e))
#'user/testlist
user> (-> testlist meta :vars)
(a b c d e)
user> (defn nil-vals-names [data]
(for [[v name] (map vector data (-> data meta :vars))
:when (nil? v)]
name))
#'user/nil-vals-names
user> (nil-vals-names testlist)
(c)
You will not be able to get a string from the variable names since Clojure will evaluate them as soon as possible to produce the testlist
=> (def testlist (a b c d e ))
("text" "text" nil 8 "")
However, you can quote the list to retrieve the symbol associated to each variable name
=> (def testlist (quote (a b c d e ))) ;; equivalent to '(a b c d e ))
(a b c d e)
And then transform these symbols into strings with the str function
=> (map str testlist)
("a" "b" "c" "d" "e")
Later, you can eval this list to retrieve the value in the context of your namespace
=> (map eval testlist)
("text" "text" nil 8 "")
Note that using eval with an external input (e.g. read-line) can create a security risk in Clojure and other languages.
Moreover, the list has to be evaluated in the same namespace as its definition. Otherwise, Clojure will not be able to resolve the symbols.
=> (ns otherns)
=> (map eval user/testlist)
java.lang.RuntimeException: Unable to resolve symbol: a in this context
The best practice in most case would be to use macros
It's quite unclear what are you trying to achieve, bit still there is a possible way.
meta function take a reference and returns a map with :name field that holds a sting with the variable name:
user=> (def foo 42)
#'user/foo
user=> (meta #'foo)
{:line 1, :column 1,
:file "/some/tmp/file.clj",
:name foo,
:ns #namespace[user]}

Using channel in `case`

(let [a (clojure.core.async/chan)]
(case a
a :foo
:bar))
#=> :bar
I would expect :foo here. What am I doing wrong?
On the other hand (condp = chan ...) does the job.
PS:
Basically I am trying to do following thing:
(require '[clojure.core.async :as a])
(let [chan1 (a/chan 10)
chan2 (a/chan 10)]
(a/>!! chan1 true)
(let [[v c] (a/alts!! [chan1 chan2])]
(case c
chan1 :chan1
chan2 :chan2
:niether)))
#=> :neither
The docs for case have the answer
The test-constants are not evaluated. They must be compile-time
literals, and need not be quoted.
The correct solution is to use cond:
(let [chan1 (ca/chan 10)
chan2 (ca/chan 10)]
(ca/>!! chan1 true)
(let [[v c] (ca/alts!! [chan1 chan2])]
(spyx (cond
(= c chan1) :chan1
(= c chan2) :chan2
:else :neither))))
;=> :chan1
Case uses unevaluated test-constants for the left-hand-side of the clause. Plain symbols, like chan1 here will match only the symbol with the same name, not the value of the local binding with that name; chan1 will match 'chan1

What is meant by destructuring in Clojure?

I'm a Java and learning clojure.
What is exactly destructuring in clojure?
I can see this blog saying:
The simplest example of destructuring is assigning the values of a
vector.
user=> (def point [5 7])
#'user/point
user=> (let [[x y] point]
(println "x:" x "y:" y))
x: 5 y: 7
what he meant by assigning the values of a vector? Whats the real use of it?
Thanks in advance
point is a variable that contains a vector of values. [x y] is a vector of variable names.
When you assign point to [x y], destructuring means that the variables each get assigned the corresponding element in the value.
This is just a simpler way of writing:
(let [x (nth point 0) y (nth point 1)]
(println "x:" x "y:" y))
See Clojure let binding forms for another way to use destructuring.
It means making a picture of the structure of some data with symbols
((fn [[d [s [_ _]]]]
(apply str (concat (take 2 (name d)) (butlast (name s)) (drop 7 (name d))) ))
'(describing (structure (of data))))
=> "destructuring"
((fn [[d e _ _ _ _ _ i n g _ _ _ _ _ s t r u c t u r e & etc]]
[d e s t r u c t u r i n g]) "describing the structure of data")
=> [\d \e \s \t \r \u \c \t \u \r \i \n \g]
Paste those ^ examples into a REPL & play around with them to see how it works.
The term "Destructuring" sounds heavier than it is.
It's like visually matching shapes to shapes. For example:
(def nums [1 2 3 4 5 6])
(let [[a b c & others] nums]
;; do something
)
Imagine the effect of the let binding as:
1 2 3 4 5 6
| | | ( )
v v v v
[a b c & others]
;; Now we can use a, b, c, others, and of course nums,
;; inside the let binding:
user=> (let [[a b c & others] nums]
(println a)
(println b)
(println c)
(println others)
(println nums))
1
2
3
(4 5 6)
[1 2 3 4 5 6]
The goal is to concisely name items of a collection, for use inside the scope of a let binding or function (i.e. within a "lexical scope").
Why "concise"? Well, without destructuring, the let binding would look like this:
(let [a (nth nums 0) ;; or (first nums)
b (nth nums 1) ;; or (second nums)
c (nth nums 2)
others (drop 3 nums)]
;; do something
)
This illustrates the basic idea. There are many details (ifs and buts, and dos and don'ts), and it's worth reading further, in depth. Here are a few resources that explain more, with examples:
My personal favourite: Jay Fields's post on Clojure Destructuring:
http://blog.jayfields.com/2010/07/clojure-destructuring.html
A gentle introduction to destructuring, from Braveclojure:
http://www.braveclojure.com/do-things/#3_3_3__Destructuring
its used to name components of a data structure, and get their values.
Say you want to have a "person" structure. In java, you would go all the way to create a class with constructors, getters and setters for the various fields, such as name, age, height etc.
In Clojure you could skip the "ceremony" and simply have a vector with 3 slots, first for name, than for age and last for height. Now you could simply name these "components" and get their values, like so:
(def person ["Fred" 30 180])
(let [[name age height] person]
(println name age height)) ;; will print: Fred 30 180
p.s - there are better ways to make a "person" in clojure (such as records etc), this is just an example to understand what destructuring does.
Destructuring is a convenience feature which allows local bindings (not variables!) to be created easily by taking apart complex data structures (seq-ables like vectors, or associatives like hash-maps), as it is described here.
Take the following example:
(let [v [1 2 3 4 5 6]
v_0 (first v)
v_1 (nth v 1)
v_rest (drop 2 v)
m {:a 1 :b 2}
m_a (get m :a)
m_b (get m :b)
m_default (get m :c "DEFAULT")]
(println v, v_0, v_1, v_rest, m, m_a, m_b, m_default))
Then the above code can be simplified using destructuring bindings like the following:
(let [[v_0 v_1 & v_rest :as v]
[1 2 3 4 5 6]
{m_a :a m_b :b m_default :c :or {m_default "DEFAULT"} :as m}
{:a 1 :b 2}]
(println v, v_0, v_1, v_rest, m, m_a, m_b, m_default))
Destructuring patterns can be used in let bindings and function parameters (fn, defn, letfn, etc.), and also in macros to return let bindings containing such destructuring patterns.
One important usage to note is with the if-letand when-let macros. The if statement is always evaluated on the whole form, even if the destructured bindings themselves evaluate to nil:
(if-let [{:keys [a b]}
{:c 1 :d 2}]
(println a b)
(println "Not this one"))
Destructuring binds a pattern of names to a complex object by binding each name to the corresponding part of the object.
To bind to a sequence, you present a vector of names. For example ...
(let [[x y] (list 5 7)] ... )
... is equivalent to
(let [x 5, y 7] ... )
To bind to a map or to a vector by index lookup, you present a map of name-to-key pairs. For example ...
(let [{x 0, y 1} [5 7]] ... )
... is equivalent to both of the above.
As others have mentioned, you can find a full description of this powerful mechanism here.

Macro quoting and unquoting

I'm trying to write a macro to require some namespaces programmatically, so that the result for a passed-in argument would be (require 'value-of-argument). If I say (defmacro r [x] `(require ~x)) then I get (require value-of-x) as expected, but I can't work out how to get the quote in there.
Edit: here's a simpler example of my problem:
(defmacro q [x] `(str ~x))
=> (map (fn [e] (q e)) (map symbol ["x" "y" "z"]))
=> ("x" "y" "z")
however,
(defmacro q [x] `(str '~x))
=> (map (fn [e] (q e)) (map symbol ["x" "y" "z"]))
=> ("e" "e" "e")
All you need is to quote the argument again, like this:
(defmacro r [x] `(require '~x))
It should do the trick.
EDIT: The above won't work since x isn't known at compile time, when the macro is expanded.
However, now that I think about it, why not just call require directly, without a macro?
This seems to work:
(require (symbol "clojure.walk"))
Does that help?
(defmacro r [x] `(require (quote ~x)))

how and why is defmulti and defmethod used? and what are the advantages?

I would like to know why defmulti & defmethod are used?
What are the advantages?
And how do you use it? Please explain what is happening in the code.
In "general terms" you would call it a if/else on steroids and in "impress me" style you would name it with "dynamic dispatch", "runtime polymorphism" etc.
Lets say you want to define a function "Add" which should work for various data types like in case of Int it should add the numbers, in case of strings it should concat the strings. Now it is very simple to implement it using if else, basically you check the type of arguments and if they are integers then add them, if they are strings then concat them else throw exception. But the problem with this is that in case you want to add support for new data type in your Add function you will need to modify the Add function, which may not be possible in cases where you don't control the source of Add such as the case it is defined in some library etc.
defmulti and defmethod allows you to solve this problem i.e adding a new case to existing function without modifying its code.
(defmulti add (fn [a b] [(type a) (type b)]))
add is the function name, the anonymous function is your if/else, basically this will be called on your add arguments and the return value of this function will be checked if there is any implementation. Now lets implement it for Integer.
(defmethod add [Integer Integer] ([a b] (+ a b)))
[Integer Integer] is sort switch case on the return value of the anonymous function we defined in defmulti and then the implementation.
Similarly we can do for strings
(defmethod add [String String] ([a b] (str a b)))
Calling it with integers
(add (int 1) (int 2))
Calling it with strings
(add "hello" "world")
Calling it with something that doesn't match our if/else i.e not implementation yet for a case will result in an exception
From what I've observed after reading the answer (and using the example provided above), the following is also helpful to understand:
when you execute the command:
(add (int 5) (int 2))
What happens is that the 'add defmulti' is executed thus producing a list:
[Integer Integer]
with that produced, it looks for any 'add defmethod' that is identified with above list i.e.:
(add [Integer Integer])
And passes on the arguments that it received.
Another way of defining the multi methods so as to make the passing of arguments clear is:
(defmulti add (fn [a b] [(type a) (type b)]))
(defmethod add [Integer Integer] [a b] (+ a b))
(defmethod add [String String] [a b] (str a b))
Then run the function as:
(add 12 73)
or
(add "thank" "you")
Multimethods helps to call the methods based on params passed. It can call the respective methods based on type of argument/or based on some properties of an argument.
Example 1 Based on type
test=> (defmulti multiply (fn [a b] [(type a) (type b)]))
#'test/multiply
test=> (defmethod multiply [Integer Integer] [a b] (* a b))
#object[clojure.lang.MultiFn 0x189f7b45 "clojure.lang.MultiFn#189f7b45"]
test=> (defmethod multiply [String String] [a b] (str a b))
#object[clojure.lang.MultiFn 0x189f7b45 "clojure.lang.MultiFn#189f7b45"]
test=> (multiply 10 10)
test=> (multiply (int 10) (int 10))
100
test=> (multiply "10" "10")
"1010"
Example 2 Based on property
test=> (defmulti mn (fn[a b] ( < a b ) ))
#'test/mn
test=> (defmethod mn true [a b] (+ a b) )
#object[clojure.lang.MultiFn 0x700f6a44 "clojure.lang.MultiFn#700f6a44"]
test=> (defmethod mn false [a b] (- a b) )
#object[clojure.lang.MultiFn 0x700f6a44 "clojure.lang.MultiFn#700f6a44"]
test=> (mn 1 2)
3
test=> (mn 2 1)
1
test=> (mn 1 1)
0