I am currently learning miniKanren by learning The Reasoned Schemer.
And I am stuck in an exercise in Chapter 5 frame 62: (run* (x) (flatten_o (a) x)), why there are three lists in output?
Good question! Where do these extra lists come from???
The problem is in the else clause of the definition of flatteno. The else clause handles the case in which s is a symbol (the symbol a, here). However, the clause also allows s to be the empty list or a pair! This is why we see three lists instead of one---the extra two lists are produced by recursive calls that succeed due to the else clause accepting non-symbol values for s.
In later versions of miniKanren we have added special constraints such as symbolo and =/= to prevent such behavior. For example, here is the same query, and flatteno, written in faster-miniKanren (https://github.com/webyrd/faster-miniKanren):
(define flatteno
(lambda (s out)
(conde
((== '() s) (== '() out))
((fresh (a d res-a res-d)
(== (cons a d) s)
(flatteno a res-a)
(flatteno d res-d)
(appendo res-a res-d out)))
((symbolo s) (== (cons s '()) out)))))
(run* (x)
(flatteno '(a) x))
=>
((a))
Note the use of the symbolo constraint in flatteno to ensure s is a symbol.
You can find a non-"Little Book" explanation of these constraints in this paper:
http://webyrd.net/quines/quines.pdf
We are trying to figure out how to include a description of these constraints in a Little Book format. The implementation of the constraints is a bit involved, which makes it hard to fit in a Little Book!
Hope this helps!
Cheers,
--Will
Related
I'm working on a Newton algorithm to count n-th root and I've encountered a problem with non-working loop. Here is the code:
(defn root [nth guess]
(if (<= guess 0) "Root doesn't exists" (count_root nth guess))
)
(defn count_root nth guess [nth guess]
(def result guess)
(def last_result result)
(def temp (power nth result))
(while (> (absolute (- result last_result)) 0.01)
(do
(def last_result result)
(def result ('fn [nth result guess temp] (* (/ 1.0 nth) (+ (* (- nth 1) result) (/ guess temp)))))
(def temp (power nth result))
)
)
(str "Result: " result)
)
(defn power [nth result]
(* result (- nth 1))
)
(defn absolute [x]
(if (>= x 0) x (- x))
)
When I'll comment out (while...) line, it counts one loop pass and the result is correct. But when there is (while...) line included, all code below is ignored.
I've rebuilt above code to something like this:
(defn power [nth result]
(* result (- nth 1))
)
(defn absolute [x]
(if (>= x 0) x (- x))
)
(defn is-good? [prev-result result]
(< (absolute (- prev-result result)) 0.01)
)
(defn improve [nth result temp]
(* (/ 1.0 nth) (+ (* (- nth 1) result) (/ result temp)))
)
(defn count-root [nth number]
(loop [result number
prev-result result
temp (power nth result)]
(let [next-result (* (/ 1.0 nth) (+ (* (- nth 1) result) (/ number temp)))])
(if (is-good? (result next-result)) result (recur next-result)))
)
(defn root [nth number]
(if (<= number 0) "Root doesn't exists" (count-root nth number))
)
But compiler throw error that next-result cannot be resolved...What's going on now?
There are a number of issues with this code. To provide you with a working example let's rewrite the root and count_root functions:
(defn power [nth result]
(* result (- nth 1)))
(defn count-root [nth guess]
(loop [result guess
last_result guess
temp (power nth result)]
(cond
(> (Math/abs (- result last_result)) 0.01)
(let [next-result (* (/ 1.0 nth) (+ (* (- nth 1) result) (/ guess temp)))]
(recur next-result
result
(power nth next-result)))
:else
(str "Result: " result))))
(defn root [nth guess]
(cond
(<= guess 0) "Root doesn't exists"
:else (count-root nth guess)))
Let's look at what was changed here, and try to explain it.
First, in the count-root function:
I suggest that you not use underscores in names. The most commonly followed Clojure convention is to use dashes to separate elements of function and definition names.
To perform a loop-with-definitions, use the loop construct to define where the loop begins, along with any needed definitions, and use recur to perform a recursive invocation of the loop with new values specified for the definitions. Note that if all the necessary definitions were given as parameters to the function count-root then no loop would be necessary and the recursion could go back to the start of the function.
I recommend that you get in the habit of using cond instead of if. The if function looks a whole lot like an if statement in other languages, and that gets us (well, OK, ME :-) into difficulties from time to time. The issue is that when you use if you have to remember to specify BOTH the "true" and "false" actions, because an if form can't be "short-cut". That is, if this was so in "other" languages you'd always have to write:
IF something
THEN true-stuff
ELSE false-stuff
ENDIF
or, in more Clojurist fashion
(if something
true-stuff
false-stuff)
In Clojure you shouldn't write
(if something
true-stuff)
because I've found that this doesn't work correctly. If you invoke the if function and specify only the true argument, as you would often do in "other" programming languages, it will compile and run, but you'll get odd results, things that can't happen will happen, and generally you'll get confused until you realize you've got an if without a "false" half or something like that. Save yourself some trouble - use cond instead of if.
4. I suggest using Math/abs instead of defining your own absolute function.
5. Use a let form to define temporary values where you won't need to loop inside the form. Here I've defined next-result as a temporary value which I'll use in the next form.
6. Use recur to tail-recursively "jump" to the next-earliest recursion point. Here the next-earliest recursion point is the loop form. If we didn't have this loop form, or some other recursion point, the function definition for count-root would serve as a recursion point. When
Next, in the root function:
the definition of the function was incorrect in the original version. I've cleaned it up here such that the function is defined with two arguments, nth and guess.
EDIT
In the original version of count_root you used the while function. Using while requires that its argument has to change, which means that it will have to deal in some manner or other with an atom; that is, it has to deal with a modifiable variable. Most of the time in Clojure, what are usually thought of as "variables" can't actually be changed. This is intentional. Clojure was intended from the outset to be used in writing multi-threaded applications, where coordinating changes to "variables" becomes a significant concern. If "variables" can't actually be changed, the need for that coordination (by means of such constructs as semaphores, critical sections, and etc) disappears. Thus, definitions of values (they're not really "variables" if they can't vary or change) are constant by default. Now, any "real" program has a need for values which change over time, and Clojure provides for such needs - but it's not the default. You must explicitly think about what needs to be modified, and you need to access those modifiable values differently.
Now, an observation for you. You may find that programming in Clojure, or in any language which makes you do things in a different manner than what you're accustomed to, will at first feel very strange, and perhaps even uncomfortably difficult. I know that's what I've gone through when learning new-to-me systems. Quite often, our thought processes get into "ruts", and anything that forces us out of those "ruts" makes us uncomfortable. But sometimes working your way through that "uncomfortable" period ends up with you having learned something valuable. If you stick with Clojure you'll learn a different way to think about software - and having multiple viewpoints from which to consider a problem is in itself a good thing.
When you're learning something new a good guide is helpful. I suggest Clojure For The Brave And True, which has the advantage that it's online edition is free-like-beer.
Best of luck.
I just got started with Clojure on Heroku, first reading this introduction.
Now in the phase of getting my hands dirty, I am facing this issue handling a database in a loop.
This is working:
(for
[s (db/query (env :database-url)
["select * from My_List"])]
; here one can do something with s, for example:
; print out (:field s)
)
But it is not enough to update variables inside the loop as I want.
Reading on the subject, I understand that Clojure having its own way of handling variables I need to use a loop pattern.
Here is what I tried:
(loop [a 0 b 1
s (db/query (env :database-url)
["select * from My_List"])]
; here I want to do something with s, for example
; print out (:field s)
; and do the following ... but it does not work!
(if (> (:otherField s) 5)
(:otherField s)
(recur (+ a (:otherField s)) b s))
)
Since I tried various ways of doing before writing this post, I know that the code above works except for the fact that I am doing something wrong concerning the database.
So here comes my question: What do I need to change to make it work?
I see, that it's hard to get to the functional thinking at first, when you're used to a different paradigm.
I don't think there is a correct explanation on “how to do this loop right”, because it's not right to do a loop here.
The two things that feel most incorrect to me:
Never do a SELECT * FROM table. This is not how relational databases are ment to be used. For example when you want the sum of all values greater than 5 you should do: SELECT SUM(field) FROM my_list WHERE field > 5
Don't think in loops (how to do it) but in what you want to do with the data:
I want to work on field :otherFIeld
I am only interested in values bigger than 5
I want the sum of all the remaining values
Then you come to something like this:
(reduce +
(filter #(> % 5)
(map :otherField
(db/query (env :database-url) ["select * from My_List"]))))
(No loop at all.)
I can define the following recursive datatype in Z3:
(declare-datatypes ()
((Tree
(leaf (content Int))
(node (left Tree) (right Tree)))))
But I cannot define the following. Do I need to declare something first? Or if that's not allow, how do I obtain an equivalent definition (where one constructor has arbitrary fields of the same type, indexed by integers)?
(declare-datatypes ()
((Tree
(leaf (content Int))
(node (children (Array Int Tree))))))
This (four year old) question is very closely related to yours: "a datatype contains a set in Z3". In the answers to that question, Leonardo de Moura says that this is not possible, and Nikolaj Bjørner gives a very detailed explanation about how one might work around the limitation. Probably you know they wrote the original paper presenting Z3 in 2008, see Z3: An Efficient SMT Solver. If we are lucky, maybe one of them will verify that recursively mixing arrays and datatypes is still not supported in Z3.
Also, what you are asking for is very similar to the tree example provided under the heading "Mutually recursive datatypes" in the rise4fun Z3 tutorial, except your question uses an array, while the the example on rise4fun uses a list. I wonder if the list-backed example on rise4fun might be modified to add an index to each list node. Something like this:
(declare-datatypes () ((Tree leaf (node (value Int) (children TreeList)))
(TreeList nil (cons (car Tree) (cdr TreeList) (index Int)))))
(assert
(forall ((treeList TreeList))
(implies
(and
(distinct treeList nil)
(distinct (cdr treeList) nil)
)
(=
(index (cdr treeList))
(+ 1 (index treeList))
)
)
)
)
(check-sat)
Unfortunately, Z3 gives unsat for this example, so evidently something is wrong here.
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))))
Is the following language context free?
L = {a^i b^k c^r d^s | i+s = k+r, i,k,r,s >= 0}
I've tried to come up with a context free grammar to generate this but I can not, so I'm assuming its not context free. As for my proof through contradiction:
Assume that L is context free,
Let p be the constant given by the pumping lemma,
Choose string S = a^p b^p c^p d^p where S = uvwxy
As |vwx| <= p, then at most vwx can contain two distinct symbols:
case a) vwx contains only a single type of symbol, therefore uv^2wx^2y will result in i+s != k+r
case b) vwx contains two types of symbols:
i) vwx is composed of b's and c's, therefore uv^2wx^2y will result in i+s != k+r
Now my problem is that if vwx is composed of either a's and b's, or c's and d's, then pumping them won't necessary break the language as i and k or s and r could increase in unison resulting in i+s == k+r.
Am I doing something wrong or is this a context free language?
I can't come up with a CFG to generate that particular language at the top of my head either, but we know that a language is context free iff some pushdown automata recognizes it.
Designing such a PDA won't be too difficult. Some ideas to get you started:
we know i+s=k+r. Equivalently, i-k-r+s = 0 (I wrote it in that order since that is the order in they appear). The crux of the problem is deciding what to do with the stack if (k+r)>i.
If you aren't familiar with PDA's or cannot use them to answer the problem, at least you know now that it is Context Free.
Good luck!
Here is a grammar that accepts this language:
A -> aAd
A -> B
A -> C
B -> aBc
B -> D
C -> bCd
C -> D
D -> bDc
D -> ε