Would anyone have a suggestion how to go about having for:
\begin{array}{cc}
Lorem & Ipsum \\
More & Stuff \\
\end{array}
Where adding or removing a c, l or r in the part after array would add or remove the & from all lines in the array environment.
Basically the same trick could then be applied to matrices or table environments.
At the least I'd be interested in how others go about this "easy-to-go-wrong", "hard-to-efficiently-alter" task.
I usually generate the tables from a different format (tab separated values or org-mode tables) in which such operations are simpler.
This is not exactly the answer, but this is how I was doing it:
Align on &, for example: C-x . &.
Select the entire column I need using regular selection commands.
Cut a rectangular area by using C-x r k.
This is not super automatic, but given some exercise isn't really a hurdle, except, perhaps, if you have to re-format some old document and make a lot of changes all at once.
EDIT
(defun latex-merge-next-column (start end column)
"Works on selected region, removes COLUMN'th ampersand
in every line in the selected region"
(interactive "r\nnColumn to merge: ")
(labels ((%nth-index-of
(line)
(let ((i -1) (times 0))
(while (and (< times column) i)
(setq i (position ?\& line :start (1+ i))
times (1+ times))) i)))
(let ((region (split-string (buffer-substring start end) "\n"))
amp-pos
replacement)
(dolist (line region)
(setq amp-pos (%nth-index-of line)
replacement
(cons (if amp-pos
(concat (subseq line 0 amp-pos)
(subseq line (1+ amp-pos)))
line) replacement)))
(kill-region start end)
(insert (mapconcat #'identity (reverse replacement) "\n")))))
This would work on the selected region and remove the n'th ampersand in every line. You could bind it to some key that is comfortable for you, say:
(global-set-key (kbd "C-c C-n") 'latex-merge-next-column)
Then C-c C-n 2 would remove every second ampersand in the selected lines.
As suggested you can make a YASnippet that according to the amount of letters in the second argument array automatically adds the appropriate amount of &s to the first row of the array:
# -*- mode: snippet -*-
# name: array
# key: arr
# expand-env: ((yas/indent-line 'fixed))
# --
\begin{array}{${1:cc}}$0
${1:$
(let ((row ""))
(dotimes (i (- (string-width yas/text) 1) row)
(setq row (concat row "& "))))
}\\\\
\end{array}
The manual exemplifies this technique. The line with (yas/indent-line 'fixed) is to avoid AUCTeX indenting the row. The reason for placing the exit point of the snippet ($0) at the end of the declaration of the array rather than at the beginning of the first row is that when placed at the beginning of the first row the exit point does not behave as expected.
The following snippet will also add as many rows as there are columns:
# -*- mode: snippet -*-
# name: array
# key: arr
# expand-env: ((yas/indent-line 'fixed))
# --
\begin{array}{${1:cc}}$0
${1:$
(let ((row "") (allrows ""))
(dotimes (i (- (string-width yas/text) 1))
(setq row (concat row "& ")))
(dotimes (i (string-width yas/text) allrows)
(setq allrows (concat allrows row "\\\\\\\\\n"))))
}\end{array}
A problem with this snippet is that it adds \\ even if there only one column but such arrays may be rare.
There seems to be problems with adding lisp comments to embedded lisp code in snippets so I simply add a commented version of only the lisp code to explain it:
;; Make an empty row with as many columns as symbols in $1 (the $1 in
;; the snippet which is what yas/text refer to)
(let ((row "") (allrows ""))
;; Make an empty row with as many columns as symbols in $1
(dotimes (i (- (string-width yas/text) 1))
(setq row (concat row "& ")))
;; Make as many rows as symbols in $1
(dotimes (i (string-width yas/text) allrows)
(setq allrows (concat allrows row "\\\\\\\\\n"))))
Building on the solution by #wvxvw, how about just using M-x align-current in the tabular/matrix/array environment and then manipulating using the block selection/insertion commands? This seems to work intelligently with escaped ampersands. I find it useful to disable wrapping during this operation. I don't find this hard to edit at all, as relatively regular re-alignment makes everything quite readable.
Related
I was writing the code that does same thing as 'reduce' function in clojure
ex) (reduce + [1 2 3 4]) = (+ (+ (+ 1 2) 3) 4).
(defn new-reduce [fn coll]
(def answer (get coll 0))
(loop [i 1]
(when (< i (count coll))
(def answer (fn answer (get coll i)))
(recur (inc i))))
answer)
In my code I used the global variable, and for me it was easier for me to understand that way. Apparently, people saying it is better to change the global variable to local variable such as let. So I tried..
(defn new-reduce [fn coll]
(let [answer (get coll 0)]
(loop [i 1]
(when (< i (count coll))
(fn answer (get coll i))
(recur (inc i))))))
To be honest, I am not really familiar with let function and even though I try really simple code, it did not work. Can somebody help me to fix this code and help me to understand how the let (local variables) really work ? Thank you. (p.s. really simple code that has loop inside let function will be great also).
Let does not create local "variables", it gives names to values, and does not let you change them after giving them the name. So introducing a let is more like defining a local constant.
First I'll just add another item into the loop expression to store the value so far. Each time through the loop we will update this to incorporate the new information. This pattern is very common. I also needed to add a new argument to the function to hold the initial state (reduce as a concept needs this)
user> (defn new-reduce [function initial-value coll]
(loop [i 0
answer-so-far initial-value]
(if (< i (count coll))
(recur (inc i) (function answer-so-far (get coll i)))
answer-so-far)))
user> (new-reduce + 0 [1 2 3])
6
This moves the "global variable" into a name that is local to the loop expression can be updated once per loop at the time you jump back up to the top. Once it reaches the end of the loop it will return the answer thus far as the return value of the function rather than recurring again. Building your own reduce function is a great way to build understanding on how to use reduce effectively.
There is a function that introduces true local variables, though it is very nearly never used in Clojure code. It's only really used in the runtime bootstap code. If you are really curious read up on binding very carefully.
Here's a simple, functional solution that replicates the behavior of the standard reduce:
(defn reduce
([f [head & tail :as coll]]
(if (empty? coll)
(f)
(reduce f head tail)))
([f init [head & tail :as coll]]
(cond
(reduced? init) #init
(empty? coll) init
:else (recur f (f init head) tail))))
There is no loop here, because the function itself serves as the recursion point. I personally find it easier to think about this recursively, but since we're using tail recursion with recur, you can think about it imperatively/iteratively as well:
If init is a signal to return early then return its value, otherwise go to step 2
If coll is empty then return init, otherwise go to step 3
Set init to the result of calling f with init and the first item of coll as arguments
Set coll to a sequence of all items in coll except the first one
Go to step 1
Actually, under the hood (with tail-call optimization and such), that's essentially what's really going on. I'd encourage you to compare these two expressions of the same solution to get a better idea of how to go about solving these sorts of problems in Clojure.
Preface
Firstly, I'm new to Clojure and programming, so I thought I'd try to create a function that solves a non-trivial equation using my natural instincts. What resulted is the desire to find a square root.
The question
What's the most efficient way to stop my square-n-map-maker function from iterating past a certain point? I'd like to fix square-n-map-maker so that I can comment out the square-maker function which provides me with the results and format I currently want to see but not the ability to recall the square-root answer (insofar as I know).
I.e. I want it to stop when it is greater than or equal to my input value
My initial thought was that instead of a keyword list, I would want it to be a map. But I'm having a very difficult time getting my function to give me a map. The whole reason I wanted a map where one member of a pair is n and another is n^2 so that I could extract the actual square root from it and it give it back to the user as the answer.
Any ideas on the best way to accomplish this? (below is the function I want to fix)
;; attempting to make a map so that I can comb over the
;; map later and recall a value that meets
;; my criteria to terminate and return result if (<= temp-var input)
(defn square-n-map-maker [input] (for [temp-var {remainder-culler input}]
(map list(temp-var) (* temp-var temp-var))
)
)
(square-n-map-maker 100) => clojure.lang.ArityException: Wrong number of args (0) passed to: MapEntry
AFn.java:437 clojure.lang.AFn.throwArity
AFn.java:35 clojure.lang.AFn.invoke
/Users/dbennett/Dropbox/Clojure Files/SquareRoot.clj:40 sqrt-range-high-end/square-n-map-maker[fn]
The following is the rest of my code
;; My idea on the best way to find a square root is simple.
;; If I want to find the square root of n, divide n in half
;; Then find all numbers in 0...n that return only a remainder of 0.
;; Then find the number that can divide by itself with a result of 1.
;; First I'll develop a function that works with evens and then odds
(defn sqrt-range-high-end [input] (/ input 2))
(sqrt-range-high-end 100) => 50
(defn make-sqrt-range [input] (range (sqrt-range-high-end (+ 1 input))))
(make-sqrt-range 100) =>(0 1 2 3 4 5 6 ... 50)
(defn zero-culler [input] (remove zero? (make-sqrt-range input)))
(zero-culler 100) =>(1 2 3 4 5 6 ... 50)
(defn odd-culler [input] (remove odd? (zero-culler input)))
(odd-culler 100) => (2 4 6 8 10...50)
(defn even-culler [input] (remove even? (zero-culler input)))
(even-culler 100) => (1 3 5 7...49)
(defn remainder-culler [input] (filter #(zero? (rem input %)) (odd-culler input)))
(remainder-culler 100) => (2 4 6 12 18)
(defn square-maker [input] (for [temp-var (remainder-culler input)]
(list (keyword (str
temp-var" "
(* temp-var temp-var)
)
)
)
)
(square-maker 100) => ((:2 4) (:4 16) (:10 100) (:20 400) (:50 2500))
Read the Error Messages!
You're getting a little ahead of yourself! Your bug has nothing to do with getting for to stop "looping."
(defn square-n-map-maker [input] (for [temp-var {remainder-culler input}]
(map list(temp-var) (* temp-var temp-var))))
(square-n-map-maker 100) => clojure.lang.ArityException: Wrong number of args (0) passed to: MapEntry
AFn.java:437 clojure.lang.AFn.throwArity
AFn.java:35 clojure.lang.AFn.invoke
Pay attention to error messages. They are your friend. In this case, it's telling you that you are passing the wrong number of arguments to MapEntry (search for IPersistentMap). What is that?
{} creates a map literal. {:key :value :key2 :value2} is a map. Maps can be used as if they were functions:
> ({:key :value} :key)
:value
That accesses the entry in the map associated with key. Now, you created a map in your first line: {remainder-culler input}. You just mapped the function remainder-culler to the input. If you grab an item out of the map, it's a MapEntry. Every MapEntry can be used as a function, accepting an index as an argument, just like a Vector:
> ([:a :b :c :d] 2)
:c
Your for is iterating over all MapEntries in {remainder-culler input}, but there's only one: [remainder-culler input]. This MapEntry gets assigned to temp-var.
Then in the next line, you wrapped this map in parentheses: (temp-var). This forms an S-expression, and expressions are evaluated assuming that the first item in the expression is a function/procedure. So it expects an index (valid indices here would be 0 and 1). But you pass no arguments to temp-var. Therefore: clojure.lang.ArityException: Wrong number of args.
Also, note that map is not a constructor for a Map.
Constructing a map
Now, on to your problem. Your square-maker is returning a list nicely formatted for a map, but it's made up of nested lists.
Try this:
(apply hash-map (flatten (square-maker 100)))
Read this page and this page to see how it works.
If you don't mind switching the order of the keys and values, you can use the group-by that I mentioned before:
(defn square-maker [input]
(group-by #(* % %) (remainder-culler input)))
(square-maker 100) => {4 [2], 16 [4], 100 [10], 400 [20], 2500 [50]}
Then you can snag the value you need like so: (first ((square-maker 100) 100)). This uses the map-as-function feature I mentioned above.
Loops
If you really want to stick with the intuitive looping concept, I would use loop, not for. for is lazy, which means that there is neither means nor reason (if you use it correctly) to "stop" it -- it doesn't actually do any work unless you ask for a value from it, and it only does the work it must to give you the value you asked for.
(defn square-root [input]
(let [candidates (remainder-culler input)]
(loop [i 0]
(if (= input (#(* % %) (nth candidates i)))
(nth candidates i)
(recur (inc i))))))
The embedded if determines when the looping will cease.
But notice that loop only returns its final value (acquaint yourself with loop's documentation if that sentence doesn't make sense to you). If you want to build up a hash-map for later analysis, you'd have to do something like (loop [i 0, mymap {}] .... But why analyze later if it can be done right away? :-)
Now, that's a pretty fragile square-root function, and it wouldn't be too hard to get it caught in an infinite loop (feed it 101). I leave it as an exercise to you to fix it (this is all an academic exercise anyway, right?).
I hope that helps you along your way, once again. I think this is a great problem for learning a new language. I should say, for the record, though, that once you are feeling comfortable with your solution, you should search for other Clojure solutions to the problem and see if you can understand how they work -- this one may be "intuitive," but it is not well-suited to Clojure's tools and capabilities. Looking at other solutions will help you grasp Clojure's world a bit better.
For more reading:
Imperative looping with side-effects.
How to position recur with loop
The handy into
Finally, this "not constructive" list of common Clojure mistakes
for is not a loop, and it's not iterating. It lazily creates a list comprehension, and it only realizes values when required (in this case, when the repl tries to print the result of the evaluation). There are two usual ways to do what you want: one is to wrap square-maker in
(first (filter some-predicate (square-maker number))) to obtain the first element in the sequence that complies with some-predicate. E.g.
(first (filter #(and (odd? %) (< 50 %)) (range)))
=> 51
The above won't realize the infinite range, obviously.
The other one is not to use a list comprehension and do it in a more imperative way: run an actual loop with a termination condition (see loop and recur).
Example:
(loop [x 0]
(if (and (odd? x) (> x 50))
x
(recur (inc x))))
set-difference works as a filter function, but only for lists. What's about arrays and strings? Are there analogous functions for these types of data? If there are no such functions, what is the proper way to implement them?
For now I use this macro to process any sequence as a list (sometimes it's useful):
(defmacro treat-as-lists (vars &body body)
(let ((type (gensym)))
`(let ((,type (etypecase ,(car vars)
(string 'string)
(vector 'vector)
(list 'list)))
,#(mapcar (lambda (x) `(,x (coerce ,x 'list)))
vars))
(coerce (progn ,#body) ,type))))
My filter:
(defun filter (what where &key key (test #'eql))
(treat-as-lists (what where)
(set-difference where what :key key :test test)))
Examples:
CL-USER> (filter "cat" "can you take this cat away?")
"n you ke his wy?"
CL-USER> (filter #(0 1) #(1 5 0 1 9 8 3 0))
#(5 9 8 3)
Since writing functions that works on all sequences types often means writing separate versions for lists and vectors, it's worthwhile to use standard functions that operate on sequences where you can. In this case, we can use position and remove-if. I've reversed the order of your arguments, in order to make this sequence-difference more like set-difference where the second argument is subtracted from the first.
(defun sequence-difference (seq1 seq2 &key (start1 0) end1 (start2 0) end2
key (key1 key) (key2 key)
test test-not)
"Returns a new sequence of the same type of seq1 that contains the
elements of the subsequence of seq1 designated by start1 and end1, and
in the same order, except for those that appear in the subsequence of
seq2 designated by start2 and end2. Test and test-not are used in the
usual way to elements produced by applying key1 (which defaults to
key) to elements from seq1 and by applying key2 (which defaults to
key) to elements from seq2."
(flet ((in-seq2 (x)
(not (null (position x seq2
:start start2 :end end2
:key key2
:test test :test-not test-not)))))
(remove-if #'in-seq2
(subseq seq1 start1 end1)
:key key1)))
(sequence-difference "can you take this cat away?" #(#\c #\a #\t))
;=> "n you ke his wy?"
(sequence-difference "can you take this cat away?" #(#\c #\a #\t) :start1 3 :start2 1)
" you ke his c wy?"
Note that the standard also includes find, which works on arbitrary sequences, but find returns "an element of the sequence, or nil." This leads to ambiguity if nil is a member of the sequence. Position, on the other hand, returns either an index (which will be a number, and thus not nil) or null, so we can reliably determine whether an element is a in sequence.
There is one important difference here in that you're always getting a copy back here. The reason for that is subjective: Since sequence functions often take start and end index arguments, it's nice to include that functionality here. But, if we ask for (sequence-difference "foobar" "boa" :start1 2) then we want to remove the characters b, o, and a from the "foobar"'s subsequence "obar". What should we return though? "for" or "r"? That is, do we include the portion of seq1 that's outside the indices? In this solution, I've made the decision not to, and thus I'm doing (remove-if … (subseq seq1 …) …), and subseq always makes a copy. Set-difference, on the other hand, may return its list-1 or list-2 argument, if appropriate. This implementation generally won't return seq1 or seq2, except in some pathological cases (e.g., the empty list).
I am trying to read data (which is actually an array) in Lisp from a text file.
I tried to use with-open-file and read-line stuff but could not achieve my goal. What I am looking for is equivalent to doing data=load('filename.txt') in MATLAB, so that I get an array called data which has loaded the whole information in filename.txt.
The text file will be in a format like
1.0 2.0 3.0 ...
1.5 2.5 3.5 ...
2.0 3.0 4.0 ...
.....
The size may also vary. Thanks a lot in advance.
The basic way to do that is to use with-open-file for getting the input stream, read-line in a loop to get the lines, split-sequence (from the library of the same name) to split it into fields, and parse-number (from the library of the same name) to transform the strings into numbers. All libraries mentioned are available from Quicklisp.
EDIT: Just to get you started, this is a simple version without validation:
(defun load-array-from-file (filename)
(with-open-file (in filename
:direction :input)
(let* ((data-lol (loop :for line := (read-line in nil)
:while line
:collect (mapcar #'parse-number:parse-number
(cl-ppcre:split "\\s+" line))))
(rows (length data-lol))
(columns (length (first data-lol))))
(make-array (list rows columns)
:initial-contents data-lol))))
You should add some checks and think about what you want to get in case they are not fulfilled:
Are the rows all the same length?
Are all fields valid numbers?
Assuming your file follows the formatting pattern you gave in your question: a sequence of numbers separated with white spaces, this is a quick snippet that should do what you want.
(defun read-array (filename)
(with-open-file (in filename)
(loop for num = (read in nil)
until (null num)
collect num)))
Another approach is to leverage the lisp reader to parse the data in the text file. To do this, I'd probably convert the entire file into a string first, and then call
(eval (read-from-string (format nil "~a~a~a" "(initial wrapper code " str ")")))
For example, if you wanted to read in a data file that is all numbers, delimited by whitespace/newlines, into a list, the previous command would look like:
(eval (read-from-string (format nil "~a~a~a" "(list " str ")")))
I followed Svante's advice. I just needed a single column in the text file, this is what I am using for this purpose.
(defun load_data (arr column filename)
(setf lnt (first (array-dimensions arr)))
(with-open-file (str (format nil "~A.txt" filename) :direction :input)
(loop :for i :from 0 :to (1- lnt) :do
(setf (aref arr i 0) (read-from-string (nth (1- column) (split-sequence:SPLIT-SEQUENCE #\Space (read-line str))))))))
Thank you all for your help.
I am stuck in a Clojure loop and need help to get out.
I first want to define a vector
(def lawl [1 2 3 4 5])
I do
(get lawl 0)
And get "1" in return. Now, I want a loop that get each number in the vector, so I do:
(loop [i 0]
(if (< i (count lawl))
(get lawl i)
(recur (inc i))))
In my mind this is supposed to set the value of i to nil, then if i is lower then the count of the lawl vector, it should get each lawl value and then increase the i variable with 1 and try again, getting the next value in the vector.
However, this does not work and I have spent some time trying to get it working and are totally stuck, would appreciate some help. I have also tried changing "if" to "when" with the same result, it doesn't provide any data the REPL just enters a new line and blink.
EDIT: Fixed the recur.
You need to consider what is "to get each lawl value" supposed to mean. Your get call does indeed "get" the appropriate value, but since you never do anything with it, it is simply discarded; Bozhidar's suggestion to add a println is a good one and will allow you to see that the loop does indeed access all the elements of lawl (just replace (get ...) with (println (get ...)), after fixing the (inc) => (inc i) thing Bozhidar mentioned also).
That said, if you simply want to do something with each number in turn, loop / recur is not a good way to go about it at all. Here are some others:
;;; do some side-effecty thing to each number in turn:
(dotimes [i (count lawl)]
(println (str i ": " (lawl i)))) ; you don't really need the get either
;; doseq is more general than dotimes, but doesn't give you equally immediate
;; acess to the index
(doseq [n lawl]
(println n))
;;; transform the lawl vector somehow and return the result:
; produce a seq of the elements of lawl transformed by some function
(map inc lawl)
; or if you want the result to be a vector too...
(vec (map inc lawl))
; produce a seq of the even members of lawl multiplied by 3
(for [n lawl
:when (even? n)]
(* n 3))
This is just the beginning. For a good tour around Clojure's standard library, see the Clojure -- Functional Programming for the JVM article by Mark Volkmann.
(recur (inc)) should be (recur (inc i))
Even so this code will just return 1 in the end, if you want a listing of the number you might add a print expression :-) Btw index based loops are not needed at all in scenarios such as this.
(loop [list [1 2 3 4 5] ]
(if (empty? list)
(println "done")
(do
(println (first list))
(recur (rest list)))))
OK, I'm about 10-1/2 years too late on this, but here goes:
The problem here is a pretty common misunderstanding of how the arguments to the if function are used. if takes three arguments - the condition/predicate, the code to be executed if the predicate is true, and the code to be executed if the predicate is false. In this case both of the true and false cases are supplied. Perhaps if we fix the indentation and add some appropriate comments we'll be able to see what's happening more easily:
(loop [i 0]
(if (< i (count lawl))
(get lawl i) ; then
(recur (inc i)))) ; else
So the problem is not that the code gets "stuck" in the loop - the problem is that the recur form is never executed. Here's how the execution flows:
The loop form is entered; i is set to 0.
The if form is entered.
The predicate form is executed and found to be true.
The code for the then branch of the if is executed, returning 1.
Execution then falls out the bottom of the loop form.
Right now I hear people screaming "Wait! WHAT?!?". Yep - in an if form you can only have a single form in the "then" and "else" branches. "But...THAT'S STUPID!" I hear you say. Well...not really. You just need to know how to work with it. There's a way to group multiple forms together in Clojure into a single form, and that's done by using do. If we want to group (get lawl i) and (recur... together we could write it as
(loop [i 0]
(if (< i (count lawl))
(do
(get lawl i) ; then
(recur (inc i))
)
)
)
As you can see, we have no "else" branch on this if form - instead, the (get... and (recur... forms are grouped together by the (do, so they execute one after the other. So after recurring its way through the lawl vector the above snippet returns nil, which is kind of ugly. So let's have it return something more informative:
(loop [i 0]
(if (< i (count lawl))
(do
(get lawl i) ; then
(recur (inc i)))
(str "All done i=" i) ; else
)
)
Now our else branch returns "All done i=5".