Error when using Integer/parseInt with map in Clojure - clojure

I'm learning Clojure and am confused by the following:
(vector "1")
;; returns ["1"]
(map vector '("1" "2" "3"))
;; returns (["1"] ["2"] ["3"])
However:
(Integer/parseInt "1")
;; returns 1
(map Integer/parseInt '("1" "2" "3"))
;; throws error "Unable to find static field: parseInt in class java.lang.Integer"
Instead, I need:
(map #(Integer/parseInt %) '("1" "2" "3"))
;; returns (1 2 3)
If I can use a function like vector with map, why can't I use Integer/parseInt?

You have to wrap it in #() or (fn ...). This is because Integer/parseInt is a Java method and Java methods can't be passed around. They don't implement the IFn interface.
Clojure is built on Java and sometimes this leaks through, and this is one of those cases.

As others have stated, you need to wrap Integer/parseInt in order to convert it from a Java method into a Clojure function:
(map #(Integer/parseInt %) '("1" "2" "3"))
The reason for this is that Clojure functions must implement the IFn interface in order to be passed as arguments into higher order functions such as map.
This is a little bit ugly if you are doing this kind of conversion many times, so I'd recommend wrapping your parse-int function as follows:
(defn parse-int [s] (Integer/parseInt s))
(map parse-int '("1" "2" "3"))
As a final alternative, you may want to use the built-in read-string function - this will return integers in your case but would also work for doubles etc.:
(map read-string '("1" "2" "3"))

Have a look at the Stack Overflow question Convert a sequence of strings to integers (Clojure). The answer says: You have to wrap Integer/parseInt in an anonymous function because Java methods aren't functions.

Related

How I can run functions, when I have only one name?

Example. We have very easy funcs.
(defn func1 []
(println "i'm func1"))
(defn func2 []
(println "i'm func2"))
And I create list with names of this functions.
(def listOfFunc '(func1 func2))
How I can run this functions, when I get name of functions from list?
Sorry for my bad english and very noob question.
Is there a specific reason why these functions are stored in a list?
If no, then you can use a vector which will result into something like this:
(def fns [func1 func2])
(map #(%) fns)
Note that this will result into a lazy seq of two nils: (nil nil). If however your functions are only for side-effects, as the ones you listed, then you can wrap them into a dorun:
(dorun (map #(%) fns))
which will return a single nil.
Now, if you still prefer using a list, you will have to resolve your symbols into the corresponding functions. So I guess something like this would work:
(map #((ns-resolve 'foo.core %)) listOfFunc)
where 'foo.core should be replaced with the namespace that has your functions.

Idiomatic no-op/"pass"

What's the (most) idiomatic Clojure representation of no-op? I.e.,
(def r (ref {}))
...
(let [der #r]
(match [(:a der) (:b der)]
[nil nil] (do (fill-in-a) (fill-in-b))
[_ nil] (fill-in-b)
[nil _] (fill-in-a)
[_ _] ????))
Python has pass. What should I be using in Clojure?
ETA: I ask mostly because I've run into places (cond, e.g.) where not supplying anything causes an error. I realize that "most" of the time, an equivalent of pass isn't needed, but when it is, I'd like to know what's the most Clojuric.
I see the keyword :default used in cases like this fairly commonly.
It has the nice property of being recognizable in the output and or logs. This way when you see a log line like: "process completed :default" it's obvious that nothing actually ran. This takes advantage of the fact that keywords are truthy in Clojure so the default will be counted as a success.
There are no "statements" in Clojure, but there are an infinite number of ways to "do nothing". An empty do block (do), literally indicates that one is "doing nothing" and evaluates to nil. Also, I agree with the comment that the question itself indicates that you are not using Clojure in an idiomatic way, regardless of this specific stylistic question.
The most analogous thing that I can think of in Clojure to a "statement that does nothing" from imperative programming would be a function that does nothing. There are a couple of built-ins that can help you here: identity is a single-arg function that simply returns its argument, and constantly is a higher-order function that accepts a value, and returns a function that will accept any number of arguments and return that value. Both are useful as placeholders in situations where you need to pass a function but don't want that function to actually do much of anything. A simple example:
(defn twizzle [x]
(let [f (cond (even? x) (partial * 4)
(= 0 (rem x 3)) (partial + 2)
:else identity)]
(f (inc x))))
Rewriting this function to "do nothing" in the default case, while possible, would require an awkward rewrite without the use of identity.

Create a clojure map threading macro ( map-> )

I'm inspired by clojure's 1.5 cond-> macro.
Similarily, I want to create a macro of the same idea, applied to the function map. However, I have no idea where to start.
For example, I can't find the source for cond->. (probably because it's not released yet)
Any suggestions?
There is the source of cond-> https://github.com/clojure/clojure/blob/master/src/clj/clojure/core.clj#L6742
there are a variety of threading macros from the pallet project folks including apply-map-> which looks close to, though not exactly what you are looking for.
(letfn [(apply-map-
[arg f arg-coll]
`(let [arg# ~arg]
(apply ~f arg#
~#(butlast arg-coll)
(apply concat ~(last arg-coll)))))]
(defmacro apply-map->
"Apply in a threaded expression.
e.g.
(-> :a
(apply-map-> hash-map 1 {:b 2}))
=> {:a 1 :b 2}"
[arg f & arg-coll]
(apply-map- arg f arg-coll))
Perhaps there will be enough examples there for you to pick out what you need.
If I understand -- you want to write a macro that takes a list of partial function calls, and for each one, adds map (or apply map) to the beginning, and the previous result to the end?
While this doesn't directly answer how to write that macro, I wanted to point out that you have a couple of alternatives.
Factor out map
This is always true for pure functions:
(=
(map g (map f coll))
(map (comp g f) coll))
The refactored version only walks the collection once, and no intermediate collections need to be made.
Here's what it looks like with threading:
(=
(->> coll
(map f)
(map g))
(map #(->> % f g) coll))
Here's a concrete example in JS.
Transducers
Transducers are another pattern for doing this kind of thing in Clojure that work on more than just map. They're sort of an abstraction over reducer functions. Clojure's map / filter / reduce (etc.) will create a transducer if called without a collection. You can chain them with comp and use them in various contexts (lazy, eager, observable, whatever). Rich Hickey's talk on them is a good intro.

Branching function composition: composition version of if/cond?

In Clojure, there are several option for composition of functions. There are composition functions for:
Apply: for 'unwrapping' arguments
Partial: for arguments that are not yet given
Comp: for piping consecutive results through multiple functions
Juxt: for applying one argument on multiple functions
However, AFAIK there are no such composition functions that include branching. Are there any functions that compose functions in a branching way, like a functional version of if or cond ?
Of course an if version is easy to make (though this implementation might not be the quickest):
(defn iff
([pred rtrue] (iff pred rtrue identity))
([pred rtrue rfalse]
(fn [& args]
(if (apply pred args)
(apply rtrue args)
(apply rfalse args)))))
There could be discussion about by default returning identity in the 'else' case is the right choice, or if nil should be returned in such case.
The use of such function could produce more easy to read code. Instead of #(if (string? %) (trim %) %) it would become (iff string? trim), or with a cond version:
(condf string? trim,
vector? (partial apply str),
:else identity)
Do other FP languages have such constructs ? I can imagine it might be handy in compositions with comp and juxt. Why doesn't Clojure ?
Bonus points for nice iff / condf implementations :)
I'm not sure if this is a direct match for what you're looking for (the question, to me, is somewhat vague), but you should look into Monads and Arrows.
Monads allow you to chain together functions with a specific "bind" function that defines how to chain them. It could do some sort of if/else pipelining, as in the Maybe and Either monads, or it could simulate state, as in the State monad.
Monads are built into Haskell (as monads) and F# (as "Workflows"). I have seen monad libraries for Clojure (check this out for one), and there are probably Arrow libraries too.
Well there could be many such composition pattern you can come up and ask why this isn't in the core language. The reason is obvious, it is not feasible. The core of the language provide you all the constructs to build such patterns. These sort of features are more of a contrib kind of thing rather than core of the language.
As far as implementation is concerned it would as simple as something shown below:
(defn condf [& args]
(let [chain (partition 2 args)]
(fn [& params]
(first (for [[p f] chain :when (or (= :else p) (apply p params))]
(apply f params))))))
(def my-func (condf string? clojure.string/trim
vector? (partial apply str)
:else identity))
(my-func "Ankur ") ==> "Ankur"
(my-func [1 2 3]) ==> "123"
(my-func '(1 2 3)) ==> (1 2 3)
This approaches the idea of Strategic Programming. You may find the following paper of interest
The Essence of Strategic Programming by
Ralf Lämmel and Eelco Visser and Joost Visser
http://homepages.cwi.nl/~ralf/eosp/
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.20.1969

How do I store Java Methods in a List in Clojure

I want to keep a list of normalizing functions for a text. How do I store .toLowercase?
I was thinking of something like this:
(def normalizing-functions (list remove-punctuations .toLowerCase))
It looks like your making a list of functions to apply to something on a regular basis. the java method is not quite a clojure function in this sense though its really
easy to wrap it up just like you would if you where going to feed it to the map function.
#(. tolowercase %)
Rather than keeping them in a list which you'll have to unpack some way later, it may just be easier to wrap .toLowerCase in a clojure function (edit: using my or Arthur's syntax) and compose it with the functions you're planning to use to normalize your data using comp:
user=> (defn remove-punctuation [st] ...removing puncutation mechanics...)
user=> (defn lower-case [st]
(.toLowerCase st))
user=> ((comp remove-punctuation lower-case) "HELLO THERE!")
"hello there"
user=> (defn normalize-data [data]
((comp remove-punctuation lower-case) data))
The memfn macro will do this in a more readable way.
(def f (memfn toLowerCase))
(f "Hello")
would return "hello". (doc memfn) has the details.