How do I pass a static method to comp in clojure? - string

It seems as though I'm having problems accessing Integer.parseInt in comp. I can access it normally like this:
user=> (Integer/parseInt "123")
123
But if I put it in comp, I get an error:
user=> (def vect-to-int (comp Integer/parseInt (partial apply str)))
java.lang.Exception: Unable to find static field: parseInt in class java.lang.Integer (NO_SOURCE_FILE:3)
It sounds to me like it's trying to find a field on Integer when it should be looking for a method. How can I use Integer.parseInt like this? And is there a better way to convert a vector of chars into an int?

Clojure functions are java methods but java methods are not clojure functions For instance Clojure functions have meta-data and such. If you want to use a java method where a Clojure function is called for then you have two choices in wrapping it up, memfn and fun or #( ) memfn is an obsolete function that wrapped up a java method in a clojure function (its good to know it exists even if its not used often). The generally accepted way to wrap up java methods is:
#(. instance method arg1 argN)
or for static methods
#(Class/MethodName arg1 argN)

(def vec-to-int (comp #(Integer/parseInt %) (partial apply str)))
Or
(def vec-to-int #(Integer/parseInt (apply str %)))
partial and comp usually aren't as succinct in Clojure as using #() to make an anonymous fn. Personally I'd write it this way:
(defn vec-to-int [x] (Integer/parseInt (apply str x)))
You can do this with plain def, but what do you gain using def instead of defn, really? Using def obscures the fact that you're defining a function. defn also sets up additional metadata for you (arglists) that def doesn't.
In any case, this is a more general way to do what you're doing:
(def vec-to-int #(bigint (apply str %)))
And still more general:
(def vec-to-int #(read-string (apply str %)))
Depends whether you want to be able to handle things other than Integers.

Related

Is there a way to create a string in a function from a list in another function in Clojure?

Im pretty new to Clojure and functional programming, im trying to use two functions to concatenate some chars intro a string. My idea is basically like this:
(defn receive [char-from-list]
(str char-from-list))
(defn send-char [list-char]
(if (empty? list-char)
(receive nil)
((receive (first list-char))(send-char (rest list-char)))))
So the idea is that I start with the function send and as a parameter write a list of chars like this:
(send-char '(\h \e \l \l \o))
The receive function with get sent one char at a time and using str it will add them all together and my final output would be: "hello".
When I try to run the code this error appears:
Execution error (ClassCastException) at automata.core/send-char (core.clj:44).
class java.lang.String cannot be cast to class clojure.lang.IFn (java.lang.String is in module java.base of loader 'bootstrap'; clojure.lang.IFn is in unnamed module of loader 'app')
Im not sure if there a way to do this or another method but I don't know how, please help. Thanks
The error is because you have 2 left parentheses in a row here:
((receive ...
Remember, in Clojure a left paren means "function call", and a string is not a function (function receive returns a string).
If you have 2 things you want to group in Clojure, you need to use a do form like:
(defn send-char [chars]
(if (empty? chars)
(receive nil)
(do
(receive (first chars))
(send-char (rest chars)))))
Having identified the source of the error, your original question still is very vague and undefined. Here are 3 ways of joining a sequence of characters into a string:
(ns tst.demo.core
(:use tupelo.core tupelo.test)
(:require
[clojure.string :as str]))
(dotest
(let-spy [chars (vec "hello")
s0 (apply str chars)
s1 (str/join chars)
s2 (reduce str "" chars)
]
(is= chars [\h \e \l \l \o])
(is= s0 "hello")
(is= s1 "hello")
(is= s2 "hello")
))
The above is based on my favorite template project. Be sure to also study the list of documentation sources.

The inner `try` interation in `fixed-point`

I am reading the fix-point of SICP:
#+begin_src emacs-lisp :session sicp :lexical t
(defvar tolerance 0.00001)
(defun fixed-point(f first-guess)
(defun close-enoughp(v1 v2)
(< (abs (- v1 v2)) tolerance))
(defun try(guess) ;;
(let ((next (funcall f guess)))
(if (close-enoughp guess next)
next
(try next))))
(try first-guess))
(fixed-point #'cos 1.0)
#+end_src
#+RESULTS:
: 0.7390822985224024
From the above case, I learned that one nature of while is the abstract concept "try"
#+begin_src ipython :session sicp :results output pySrc/sicp_fixedpoint2.py
import math
def fixed_point(f, guess):
while True:
nex = f(guess)
if abs(guess-nex) < 0.0001:
return nex
else:
guess = nex #local assignment is nature of lambda
print(fixed_point(math.cos, 1))
#+end_src
#+RESULTS:
: 0.7390547907469174
So I could write iteration in python just with the effective functional abstraction thinking.
When reflect on try, more than "try is a while in iteration", what it teach me?
It could be reframed without try, but return return fixed_point(f, nex) directly.
#+begin_src ipython :session sicp :results output :tangle pySrc/sicp_fixedpoint.py
import math
tolerance = 0.00001
def fixed_point(f, guess):
def good_enoughp(a, b):
return abs(a-b) < tolerance
nex = f(guess)
if good_enoughp(guess, nex):
return nex
else:
return fixed_point(f, nex)
print(fixed_point(math.cos, 1))
#+end_src
#+RESULTS:
: 0.7390822985224024
So why SICP introduced try here, I guess efficiency might not be the author's key consideration.
Test with elisp
#+begin_src emacs-lisp :session sicp :lexical t
(defvar tolerance 0.00001)
(defun fixed-point(f guess)
(defun close-enoughp(v1 v2) ;
(< (abs (- v1 v2)) tolerance))
(let ((next (funcall f guess)))
(if (close-enoughp guess next)
next
(fixed-point f next)))
)
;;(trace-function #'fixed-point)
(fixed-point #'cos 1.0)
#+end_src
#+RESULTS:
: 0.7390822985224024
It works as expected.
It seems that return fixed-point f next is a bit cleaner than a inner iteration with try.
What's the consideration of SICP here, what was intended to teach?
It's the opposite: it's cleaner and more efficient with try because it doesn't need to redefine the good-enough-p.
(also, you're not supposed to use recursion in Python).
The version with try is better than the version which calls the top function, fixed-point, because fixed-point contains inner definitions, of the functions good-enough-p and try. A simple-minded compiler would compile it so that on each call it actually makes those definitions anew, again and again, on each call. With try there's no such concern as it is already inside the fixed-point's inner environment where good-enough-p is already defined, and so try can just run.
(correction/clarification: the above treats your code as if it were Scheme, with internal defines instead of the Common Lisp with defuns as you show. SICP is Scheme, after all. In Common Lisp / ELisp there's not even a question -- the internal defuns will always be performed, on each call to the enclosing function, just (re)defining the same functions at the top level over and over again.)
Incidentally, I like your Python loop translation, it is a verbatim translation of the Scheme's tail-recursive loop, one to one.
Your while translation is exactly what a Scheme compiler is supposed to be doing given the first tail-recursive Scheme code in your question. The two are exactly the same, down to the "horrible while True ... with an escape" which, personally, I quite like for its immediacy and clarity. Meaning, I don't need to keep track of which value gets assigned to what variable and which variable gets returned in the end -- instead, a value is just returned, just like it is in Scheme.
The natural way to write something like this in Python is something like this, I think:
tolerance = 0.00001
def fixed_point(f, first_guess):
guess = first_guess
next_guess = f(guess)
def close_enough(a, b):
return (abs(a - b) < tolerance)
while not close_enough(guess, next_guess):
guess = next_guess
next_guess = f(guess)
return next_guess
This:
uses a while loop rather than recursion in the way that is natural in Python;
doesn't use some horrible while True ... with an escape which is just confusing.
(In fact, since function-call in Python is generally very slow, it is probably more natural to open-code the call to close_enough and remove the local function altogether.)
But this is imperative code: it's full of assignment (the first two 'assignments' are really bindings of variables as Python doesn't distinguish the two syntactically, but the later assignments really are assignments). We want to express this in a way which doesn't have assignment. We also want to replace it by something which does not use any looping constructs or expresses those looping constructs in terms of function calls.
We can do this in two ways:
we can treat the top-level function as the thing we call recursively;
we can define some local function through which we recurse.
Which of these we do is really a choice, and in this case it probably makes little difference. However there are often significant advantages to the second approach: in general the top-level function (the function that is in some interface we might be exposing to people) may have all sorts of extra arguments, some of which may have default values and so on, which we really don't want to have to keep passing through the later calls to it; the top-level function may also just not have an appropriate argument signature at all because the iterative steps may be iterating over some set of values which are derived from the arguments to the top-level function.
So, it's generally better to express the iteration in terms of a local function although it may not always be so.
Here is a recursive version in Python which takes the chance to also make the signature of the top-level function sightly richer. Note that this approach would be terrible style in Python since Python does not do anything special with tail calls. The code is also littered with returns because Python is not an expression language (don't believe people who say 'Python is like Lisp': it's not):
default_tolerance = 0.00001
def fixed_point(f, first_guess, tolerance=default_tolerance):
guess = first_guess
next_guess = f(guess)
def close_enough(a, b):
return (abs(a - b) < tolerance)
def step(guess, next_guess):
if close_enough(guess, next_guess):
return next_guess
else:
return step(next_guess, f(next_guess))
return step(first_guess, f(first_guess))
Well, in Scheme this is much more natural: here is the same function written in Scheme (in fact, in Racket):
(define default-tolerance 0.00001)
(define (fixed-point f initial-guess #:tolerance (tolerance default-tolerance))
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(define (try guess next)
(if (close-enough? guess next)
next
(try next (f next))))
(try initial-guess (f initial-guess)))
The only thing that is annoying about this is that we have to kick-off the iteration after defining try. Well, we could avoid even that with a macro:
(define-syntax-rule (iterate name ((var val) ...) form ...)
(begin
(define (name var ...)
form ...)
(name val ...)))
And now we can write the function as:
(define (fixed-point f initial-guess #:tolerance (tolerance default-tolerance))
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(iterate try ((guess initial-guess) (next (f initial-guess)))
(if (close-enough? guess next)
next
(try next (f next)))))
Well, in fact we don't need to write this iterate macro: it's so useful in Scheme that it already exists as a special version of let called 'named let':
(define (fixed-point f initial-guess #:tolerance (tolerance default-tolerance))
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(let try ((guess initial-guess) (next (f initial-guess)))
(if (close-enough? guess next)
next
(try next (f next)))))
And with any of these versions:
> (fixed-point cos 0)
0.7390822985224023
> (fixed-point cos 0 #:tolerance 0.1)
0.7013687736227565
Finally a meta-comment: I don't understand why you seem to be trying to learn Scheme using Emacs Lisp. The two languages are not alike at all: if you want to learn Scheme, use Scheme: there are probably hundreds of Scheme systems out there, almost all of which are free.
Scheme permits redefinition of top-level symbols, such as fixed-point; even the function f could redefine it! Compilers (and interpreters) need to take this into consideration, and check for a redefinition every call of fixed-point. On the other hand, try is not visible outside the definition of fixed-point, so f cannot redefine it. So, the compiler (or interpreter) can turn this tail recursive function into a loop.

how to retrieve a key in a map whose value contains a particular substring in clojure?

i need to retrieve the key whose value contains a string "TRY"
:CAB "NAB/TRY/FIGHT.jar"
so in this case the output should be :CAB .
I am new to Clojure, I tried a few things like .contains etc but I could not form the exact function for the above problem.its easier in few other languages like python but I don't know how to do it in Clojure.
Is there a way to retrieve the name of the key ?
for can also filter with :when. E.g.
(for [[k v] {:FOO "TRY" :BAR "BAZ"}
:when (.contains v "TRY")]
k)
First, using .contains is not recommended - first, you are using the internals of the underlying language (Java or JavaScript) without need, and second, it forces Clojure to do a reflection as it cannot be sure that the argument is a string.
It's better to use clojure.string/includes? instead.
Several working solutions have been already proposed here for extracting a key depending on the value, here is one more, that uses the keep function:
(require '[clojure.string :as cs])
(keep (fn [[k v]] (when (cs/includes? v "TRY") k))
{:CAB "NAB/TRY/FIGHT.jar" :BLAH "NOWAY.jar"}) ; => (:CAB)
The easiest way is to use the contains method from java.lang.String. I'd use that to map valid keys, and then filter to remove all nil values:
(filter some?
(map (fn [[k v]] (when (.contains v "TRY") k))
{:CAB "NAB/TRY/FIGHT.jar" :BLAH "NOWAY.jar"}))
=> (:CAB)
If you think there is at most one such matching k/v pair in the map, then you can just call first on that to get the relevant key.
You can also use a regular expression instead of .contains, e.g.
(fn [[k v]] (when (re-find #"TRY" v) k))
You can use some on your collection, some will operate in every value in your map a given function until the function returns a non nil value.
We're gonna use the function
(fn [[key value]] (when (.contains values "TRY") key))
when returns nil unless the condition is matched so it will work perfectly for our use case. We're using destructuring in the arguments of the function to get the key and value. When used by some, your collection will indeed be converted to a coll which will look like
'((:BAR "NAB/TRY/FIGHT.jar"))
If your map is named coll, the following code will do the trick
(some
(fn [[key value]] (when (.contains value "TRY") key))
coll)

What is the best way to append to an array in each iteration of a loop on a map using clojure?

I have created a structure which builds a URL query from a map but it is not thread-safe since it's relying on a defined variable which probably isn't needed so what is the best way to do this?
(def charset "UTF-8")
(defn make-query
[params]
(do
(def tmpa [])
(doseq [keyval params]
(def tmpa
(into tmpa
[(str
(java.net.URLEncoder/encode (name (first keyval)) charset)
"="
(java.net.URLEncoder/encode (apply (first keyval) [params]) charset)
)]
)
)
)
(clojure.string/join "&" tmpa)
)
)
The use of nested defs is not really the way to go when you need to work with an intermediate value in a function, that's what the let form is for. Also note that def creates a top level var, so even after the make-query function returns, you will still have a tmpa var lying around in the namespace where you declared the function.
The function you posted has an imperative style since it's using doseq (which is by definition to be used for side-effects) and changing the value of the tmpa var in every iteration of the loop.
A functional approach would be reduceing the key-value pairs and build the result by concatenating the key and value to the query string in each call to the reducing function. The following is an example of how this can be achieved:
(def charset "UTF-8")
(defn make-query
[params]
(reduce (fn [query [k v]]
(str query
(java.net.URLEncoder/encode (name k) charset)
"="
(java.net.URLEncoder/encode (str v) charset)
"&"))
""
params))
(make-query {:name "clojure" :year 2014})
;= "name=clojure&year=2014&"
It takes some time to get used to thinking this way, when one comes from an imperative and OOP background, but with practice it gets a lot easier.
Hope it helps.

Lisp: How to override default string representation for CLOS class?

In Common Lisp, how can I override the default string representation of a CLOS class so that calls to format or princ will print something intelligible, even when objects of that class are embedded within other types, such as lists or arrays?
For example, if I call (format t "~a~%" x) when x holds an instance of my solution class, I want it to print something like #<SOLUTION genes: #(1 2 3) scores: #(4 5) rank: 6> instead of #<SOLUTION {BB7CD31}>.
So far, all I have managed to figure out is writing custom functions to handle printing structures that I know will contain instances of this class, but this is tedious. Surely Lisp provides some way to get this functionality for free?
You should be looking at print-object and print-unreadable-object. Suppose you have a class named FOO like so:
(defclass foo ()
((name :accessor foo-name)))
And you want to print instances like this: #<FOO "xyz"> where "xyz" is the content of slot name. In this case, the following implementation of print-object would do what you want:
(defmethod print-object ((obj foo) out)
(print-unreadable-object (obj out :type t)
(format out "~s" (foo-name obj))))
Check out print-object.
If you also look 22.1.3.13 Printing Other Objects it suggests print-unreadable-object as a common format macro for such situations

Resources