Can anyone explain me the stets of this clojure function
(defn to-list [{:keys [key left right] :as tree}]
(when tree
`(~#(to-list left) ~key ~#(to-list right))))
So the to-list function expects a map that has some of three keys, namely key, left and right. This map can be accessed also by the name tree. See this for argument destructuring. Then you have a syntax quote (see this for details). It is roughly equivalent to
(clojure.core/seq (clojure.core/concat (to-list left)
(clojure.core/list key)
(to-list rirght)))
So basically if you have nil for tree, it will return nil (which seems reasonable). If you have a tree with a key left (which is either nil or also a map possibly with keys key, left and right), then left tree is recursively printed, then the key is added, then if you have a key right, the right tree is printed recursively. If at any step you have only left or only right, the call (to-list left) will yield nil and the rest will work as already explained.
I hope this helps.
NOTE I don't have a clojure repl right now, so I did not test what is the exact equivalent of syntax-quote, but it should be very something similar to the thing that I wrote.
Related
Here's some code I wrote, using clojure.core.match, which performs a pretty common programmng task. A function takes some "commands" (or "objects", "records", or whatever you prefer to call them), has to do something different with each type, and has to destructure them to figure out exactly what to do, and different command types might have to be destructured differently:
(defn action->edits [g action]
"Returns vector of edits needed to perform action in graph g."
(match action
[:boost from to]
[[:add-edge from to 1.0]]
[:retract from to]
[[:remove-edge from to]]
[:normalize from to] ; a change has just been made to from->to
(map (fn [that] [:remove-edge from that])
(successors-except g from to))
[:recip-normalize to from] ; a change has just been made to from->to
[]
[:reduce-to-unofficial from to competitor]
[[:remove-edge from to] (make-competitive-edge from competitor]))
I'm mostly imitating the way people commonly use the pmatch macro in Scheme. I'd like to know what's the idiomatic way to do this in Clojure.
Here's what I like about the above code:
It's very readable.
It was effortless to write.
Here's what I don't like:
Accessing the from and to fields from anywhere but inside a match macro is extremely unreadable and error-prone. For example, to extract the from element from most of the action vectors, you write (action 1). That code will break if I ever add a new action, and it breaks right now on :recip-normalize.
The code generated by match is inefficient: it searches by repeatedly throwing and catching exceptions. It doesn't just generate a big nested if.
I experimented a little with representing the commands as maps, but it seemed to get verbose, and the name of the command doesn't stand out well, greatly reducing readability:
(match action
{:action :boost :from from :to to}
[{:edit :add-edge :from from :to to :weight 1.0}]
{:action :retract :from from :to to}
[{:edit :remove-edge :from from :to to}]
. . .)
Probably future versions of match will generate better code, but the poor code generated now (and lack of support for records) suggests that in Clojure, people have been handling this kind of thing happily for years without match. So how do you do this kind of thing in Clojure?
I would utilize clojure's build-in destructuring facilities, since I do not see a requirement for core.match here - but I might be missing something.
For example:
(defn action->edits [g [action from to]]
(condp = action
:boost "boosting"
:retract "retracting"
:normalize-ksp-style (recur g [:boost from to])
nil))
(action->edits 2 [:normalize-ksp-style 1 2])
;=> "boosting"
I am currently learning Scheme and have just learned about inductive sets and recursion. I currently defined a datatype bTree which is a binary tree
(define-datatype bTree bTree?
(leaf
(datum number?))
(node
(value symbol?)
(left bTree?)
(right bTree?)))
Which works fine. I want to create a function that when given a bTree, would return a list of paths from the root (which are also lists), to each of the leaves, in which left is indicated by a 0 and right is indicated by 1.
(define bTree-path
(lambda (tree)
(cases bTree tree
(leaf (datum) '())
(node (value left right)
(list (cons 0 (bTree-path left)) (cons 1 (bTree-path right)))))))
My thought process was that if it sees a leaf, it returns nothing to the current list. However if it is a node, a new list is created. In this list the function is called recursively for both left and right subtrees with a cons operator with 0 and 1 respectively (meaning on step left and one step right). This quickly was proven wrong as the result for a test tree included nested lists. The result should be something like ( (0 1) (0 0) (1) ) which means there are 3 leaves that can be found by going left twice, right once or left and then right.
Working from the leaves to the root will not work because you will not know what whether the leaf is a left or right leaf. Calling list everytime a node is found is causing the nesting. Is there a way that can simply call two lists at the same time using two recursive calls with left and right subtrees? Possibly a function or operation?
Since the result of (bTree-path left) is (or at least it should be) a list of all the paths from left to the leaves in that subtree, you need to add 0 to each one of those paths.
Likewise for the right subtree.
The function that does something to each element of a list is map:
(map (lambda (path) (cons 0 path)) (bTree-path left))
Next, you want to merge your two lists of paths – from the left and from the right – into one list, and the function that does that is append.
Putting it all together left as an exercise.
Since version 22 of Emacs, we can use \,(function) for manipualting (parts of) the regex-search result before replacing it. But – this is mentioned often, but nonetheless still the truth – we can use this construct only in the standard interactive way. (Interactive like: By pressing C-M-% or calling query-replace-regexp with M-x.)
As an example:
If we have
[Foo Bar 1900]
and want to get
[Foo Bar \function{foo1900}{1900}]
we can use:
M-x query-replace-regexp <return>
\[\([A-Za-z-]+\)\([^0-9]*\) \([0-9]\{4\}\)\]
[\1\2 \\function{\,(downcase \1)\3}{\3}]
to get it done. So this can be done pretty easy.
In my own defun, I can use query only by replacing without freely modifying the match, or modify the prepared replaced string without any querying. The only way I see, is to serialize it in such a way:
(defun form-to-function ()
(interactive)
(goto-char (point-min))
(while (query-replace-regexp
"\\[\\([A-Za-z-]+\\)\\([^0-9]*\\) \\([0-9]\\{4\\}\\)\\]"
"[\\1\\2 \\\\function{\\1\\3}{\\3}]" ))
(goto-char (point-min))
(while (search-forward-regexp "\\([a-z0-9]\\)" nil t)
(replace-match (downcase (match-string 1)) t nil)
)
)
For me the query is important, because I can't be sure, what the buffer offers me (= I can't be sure, the author used this kind of string always in the same manner).
I want to use an elisp function, because it is not the only recurring replacement (and also not only one buffer (I know about dired-do-query-replace-regexp but I prefer working buffer-by-buffer with replace-defuns)).
At first I thought I only miss something like a query-replace-match to use instead of replace-match. But I fear, I am also missing the easy and flexible way of rearrange the string the the query-replace-regexp.
So I think, I need a \, for use in an defun. And I really wonder, if I am the only one, who is missing this feature.
If you want your rsearch&replace to prompt the user, that means you want it to be interactive, so it's perfectly OK to call query-replace-regexp (even if the byte-compiler will tell you that this is meant for interactive use only). If the warning bothers you, you can either wrap the call in with-no-warnings or call perform-replace instead.
The docstring of perform-replace sadly doesn't (or rather "didn't" until today) say what is the format of the replacements argument, but you can see it in the function's code:
;; REPLACEMENTS is either a string, a list of strings, or a cons cell
;; containing a function and its first argument. The function is
;; called to generate each replacement like this:
;; (funcall (car replacements) (cdr replacements) replace-count)
;; It must return a string.
The query-replace-function can handle replacement not only as a string, but as a list including the manipulating elements. The use of concat archives building an string from various elements.
So one who wants to manipulate the search match by a function before inserting the replacement can use query-replace-regexp also in a defun.
(defun form-to-function ()
(interactive)
(goto-char (point-min))
(query-replace-regexp
"\\[\\([A-Za-z-]+\\)\\([^0-9]*\\) \\([0-9]\\{4\\}\\)\\]"
(quote (replace-eval-replacement concat "[\\1\\2 \\\\function{"
(replace-quote (downcase (match-string 1))) "\\3}{\\3}]")) nil ))
match-string 1 returns the first expression of our regexp-search.
`replace-quote' helps us doublequoting the following expression.
concat forms a string from the following elements.
and
replace-eval-replacement is not documented.
Why it is in use here nevertheless, is because of emacs seems to use it internally, while performing the first »interactive« query-replace-regexp call. At least is it given by asking emacs with repeat-complex-command.
I came across repeat-complex-command (bound to [C-x M-:].) while searching for an answer in the source code of query-replace-regexp.
So an easy to create defun could be archieved by performing the standard search and replace way as told in the question and after first sucess pressing [C-x M-:] results in an already Lisp formed command, which can be copied and pasted in a defun.
Edit (perform-replace)
As Stefan mentioned, one can use perform-replace to avoid using query-replace-regexp.
Such a function could be:
(defun form-to-function ()
(interactive)
(goto-char (point-min))
(while (perform-replace
"\\[\\([A-Za-z-]+\\)\\([^0-9]*\\) \\([0-9]\\{4\\}\\)\\]"
(quote (replace-eval-replacement concat "[\\1\\2 \\\\function{"
(replace-quote (downcase (match-string 1))) "\\3}{\\3}]"))
t t nil)))
The first boolean (t) is a query flag, the second is the regexp switch. So it works also perfectly, but it didn't help finding the replacement expression as easy as in using \,.
I'm trying to write a procedure Huffman-leaves; the procedure returns a list of pairs from a created huffman tree.
Example on how it runs
(huffman-leaves sample-tree)
->((A . 8) (C . 5) (B . 1) (D . 1))
What I've comed up with but got writers block...
(define (huffman-leaves tree)
(define (huffman-get-pairs current-branch pairs)
(if (or (null? tree) (null? current-branch))
pairs
(let ((next-branch
(get-branch (car current-branch) current-branch)))
(not (member? next-branch pairs)
(if (leaf? next-branch)
(cons (append pairs next-branch)
(display pairs)
(huffman-get-pairs (cadr current-branch) pairs))
(huffman-get-pairs next-branch pairs))))))
(huffman-get-pairs tree '()))
(member? item 'list) #if item in list return #t else #false
I know that I'm doing something wrong but I can't see it.
How can I stop a search in a huffman-tree in scheme? Any tip that I should be doing different?
I recommend:
Write a data definition for Huffman Tree
Make example input huffman trees, encoded according to your data definition from step 1, and expected outputs (lists of leaves, in this case).
Follow the design recipe to build a basic template for the huffman-leaves function.
Fill in the ... in your template according to the examples you built from step 2.
Translate your examples from step 2. into tests, and test your code from step 4.
Sorry if the above seems vague, but it is the best advice I can give with the level of detail (or lack thereof) you have supplied in this question thus far. If you can provide answers for the steps above, and say explicitly which step you are blocked on, then we can help you get over your writers block in a more systematic way.
If you prefer real code, here is one direction you could go in to make a very generic solution for your problem:
;; make-visitor : (X -> Y) (X -> [Listof X]) (Y [Listof Z] -> Z) -> Z
;; Very generic descend+map+recombine routine
;; (note X, Y, Z are implicitly universally quantified above).
(define (make-visitor transform children combine)
(lambda (x)
(let rec ((x x)) ;; rec : X -> Z
(combine (transform x)
(map rec (children x))))))
;; ... the hard bit is coming up with the appropriate lambda
;; expressions for `transform`, `children`, and `combine` above.
(define leaves
(make-visitor (lambda (x) ...)
(lambda (x) ...)
(lambda (y zs) ...)))
I don't actually recommend trying to jump directly to a solution of this form; you will be better off if you try to follow the design recipe and make a direct solution to your problem. But once you have done that, it can be an educational exercise to see if you can retrofit your own solution onto the generic routine above.
I recently started reading Paul Grahams 'On Lisp', and learning learning clojure along with it, so there's probably some really obvious error in here, but I can't see it: (its a project euler problem, obviously)
(ns net.projecteuler.problem31)
(def paths (ref #{}))
; apply fun to all elements of coll for which pred-fun returns true
(defn apply-if [pred-fun fun coll]
(apply fun (filter pred-fun coll)))
(defn make-combination-counter [coin-values]
(fn recurse
([sum] (recurse sum 0 '()))
([max-sum current-sum coin-path]
(if (= max-sum current-sum)
; if we've recursed to the bottom, add current path to paths
(dosync (ref-set paths (conj #paths (sort coin-path))))
; else go on recursing
(apply-if (fn [x] (<= (+ current-sum x) max-sum))
(fn [x] (recurse max-sum (+ x current-sum) (cons x coin-path)))
coin-values)))))
(def count-currency-combinations (make-combination-counter '(1 2 5 10 20 50 100 200)))
(count-currency-combinations 200)
When I run the last line in the REPL, i get the error:
<#CompilerException java.lang.IllegalArgumentException: Wrong number of args passed to: problem31$eval--25$make-combination-counter--27$recurse--29$fn (NO_SOURCE_FILE:0)>
Apart from the question where the error is, the more interesting question would be: How would one debug this? The error message isn't very helpful, and I haven't found a good way to single-step clojure code, and I can't really ask on stack overflow every time I have a problem.
Three tips that might make your life easier here:
Wrong number of args passed to: problem31$eval--25$make-combination-counter--27$recurse--29$fn (NO_SOURCE_FILE:0)>
Tells you roughly where the error occurred: $fn at the end there means anonymous function and it tells you it was declared inside recurse, which was declared inside make-combination-counter. There are two anonymous functions to choose from.
If you save your source-code in a file and execute it as a script it will give you a full stack trace with the line numbers in the file.
at net.projecteuler.problem31$apply_if__9.invoke(problem31.clj:7)
Note you can also examine the last exception and stack trace from within the REPL by examining *e eg: (.stackTrace *e) The stack trace is at first quite daunting because it throws up all the Java internals. You need to learn to ignore those and just look for the lines that refer to your code. This is pretty easy in your case as they all start with net.projecteuler
You can name your anonymous functions to help more quickly identify them:
(fn check-max [x] (<= (+ current-sum x) max-sum))
In your case using all this info you can see that apply-if is being passed a single argument function as fun. Apply does this (f [1 2 3]) -> (f 1 2 3). From your comment what you want is map. (map f [1 2 3]) -> (list (f 1) (f 2) (f 3)). When I replace apply with map the program seems to work.
Finally, if you want to examine values you might want to look into clojure-contrib.logging which has some helpers to this effect. There is a spy macro which allows you to wrap an expression, it will return exactly the same expression so it does not affect the result of your function but will print out EXPR = VALUE, which can be handy. Also on the group various people have posted full tracing solutions. And there is always the trusty println. But the key skill here is being able to identify precisely what blew up. Once you know that it is usually clear why, but sometimes printouts are needed when you can't tell what the inputs are.
dont have a REPL on me though it looks like:
(defn apply-if [pred-fun fun coll]
(apply fun (filter pred-fun coll)))
takes a list like '(1 2 3 4 5) filters some of them out '(1 3 5)
and then creates a function call like (fun 1 3 5)
and it looks like it is being called (apply-if (fn [x] with a function that wants to receive a list of numbers as a single argument.
you could change the apply-if function to just pass call to the fun (with out the apply) or you could change the call to it to take a function that takes an arbitrary number of arguments.