I am currently learning scheme as part of a course I am taking. The way it has been taught to me is with generous use of the eval expression, and most of the provided examples I am testing do not work as described. The more I read, it becomes obvious that I should not be using eval so freely. I have seen some circumvention methods in javaScript but I am looking for something specific to Scheme.
This link provides some info about when eval may necessary. That doesn't really help me figure out a good circumvention method.
This link has more good info but doesn't give any way to avoid eval in my situation.
This link came closest to answering my question, and helped me to understand why eval does not necessarily work as expected, but I am still unclear on what a good replacement for the eval expression would be.
What I am looking for is the standard way to do this :
(define (add a_list)
(cond
((null? a_list) 0)
(eval(cons '+ a_list)))
)
(add '(3 4 8 12 30))
without eval so that it returns 57. Currently it returns (+ 3 4 8 12 30).
This link seems to suggest that, say, (+ 3 4) would automatically evaluate to 7, but I am getting just the list printed back to me as an expression with no evaluation.
It will work fine written the following ways:
(define (add a_list)
(cond
((null? a_list) 0)
(eval(eval(cons '+ a_list))))
)
(add '(3 4 8 12 30))
returns 57 but one of the evals seems to do nothing. And :
(define (add a_list)
(eval(cons '+ a_list))
)
(add '(3 4 8 12 30))
returns 57 but does not check for an empty list.
Any help removing it altogether (or only using it if absolutely necessary) would be greatly appreciated.
Thanks in advance!
For the examples mentioned, you don't need eval, a simple apply will work. And your suspicions are correct, we should avoid using eval most of the time - it's considered "evil".
(define (add a_list)
(apply + a_list))
Related
I am using Clojure to do the following task -
Write a function named get-divisors which takes a number n as input and returns the all the numbers between 2 and √𝑛 inclusive
I have this code so far, that seems to be working as expected:
(defn get-divisors [n]
(str (range 2 (Math/sqrt n))))
The user inserts and input and the code shall display all numbers between 2 and the square root of that particular number. (I know! get-divisors is a horrible name for the function)
I type (get-divisors 101) I get the following output
"(2 3 4 5 6 7 8 9 10)" which is correct.
However, the issue is when I use the number 4 I get a result of nil or () when I should in-fact get 2. Or when I enter 49 I should get all numbers between 2 and 7 but I only get all the numbers between 2 and 6.
I have searched online for some information. I am new to Clojure however, the information on this programming seems to be scarce as opposed to the likes of Java, JavaScript. I have read another thread which was based on a similar situation to mind, however, the suggestions/answers didn't work for me unfortunately.
I would appreciate any help. Thank you.
Please see the Clojure CheatSheet. range does not include the upper bound. So, in general, you probably want something like
(range 2 (inc n))
or in your case
(range 2 (inc (Math/floor (Math/sqrt n))))
Also check out http://clojure.org
I start to read/work on clojure and for that I start to read in parallel 'Programming Clojure' and 'Practical Clojure' books. I saw there one example of how lazy sequence working and for me was very clear in order to understand how lazy-seq work but unfortunately it doesn't work or at least not how I expect.
here is the example:
(defn square[x]
(do
(println "[current.elem=" x "]")
(* x x))
)
(def var-00 (map square '(1 2 3 5 6 4)))
when I call:
var-00
, I expect that no message to print on console(REPL) but I got the follow result:
([current.elem= 1 ][current.elem= 2 ]1 [current.elem= 3 ]4 [current.elem= 5 ]9 [current.elem= 6 ]25 [current.elem= 4 ]36 16)
this mean that the function map was called even I expect to nothing happen since 'var-00' is just a reference to function 'map'; and more awkward from my point of view, if I call:
(nth var-00 2)
I got:
[current.elem= 1 ][current.elem= 2 ][current.elem= 3 ]9
, and if I call again:
(nth var-00 3)
I got:
[current.elem= 1 ][current.elem= 2 ][current.elem= 3 ][current.elem= 5 ]25;
previous elements(1,2,3) was computed again I my opinion those elements should be 'cached' by first call and now only element 5 should be computed. Did I do something wrong or I didn't fully understand how lazy sequence working in clojure ? As a mention I use IntellijIDEA and LaClojure plugin to run the program.
Thanks Sorin.
Just checked your coed in Clojure REPL, it works fine for me. Every element got printed only once (when it's evaluated the first time).
I even tried your example in Clojure online REPL:
But there is one thing that you got wrong. REPL executes each command and then prints its results, so when you type var-00 REPL resolves the symbol and then, in order to print it, executes the whole lazy sequence:
It have nothing to do with lazy sequences, it's just how REPL works:
Lazy Evaluation dosen't mean that things will be cached. It means that inside a calculation an element will only be evaluated, if it is needed for the result. If an element is needed twice for the result, it might be evalueated twice.
If you want to have automatic caching of elements there is the memoize function, which will return a transformed version of the input function with added caching of results. This is also a easy way to implement dynamic programming
I would like to know how can I construct a regex to know if a number in base 2 (binary) is multiple of 3. I had read in this thread Check if a number is divisible by 3 but they dont do it with a regex, and the graph someone drew is wrong(because it doesn't accept even numbers). I have tried with: ((1+)(0*)(1+))(0) but it doesn't works for some values. Hope you can help me.
UPDATE:
Ok, thanks all for your help, now I know how to draw the NFA, here I left the graph and the regular expresion:
In the graph, the states are the number in base 10 mod 3.
For example: to go to state 1 you have to have 1, then you can add 1 or 0, if you add 1, you would have 11(3 in base 10), and this number mod 3 is 0 then you draw the arc to the state 0.
((0*)((11)*)((1((00) *)1) *)(101 *(0|((00) *1 *) *0)1) *(1(000)+1*01)*) *
And the other regex works, but this is shorter.
Thanks a lot :)
I know this is an old question, but an efficient answer is yet to be given and this question pops up first for "binary divisible by 3 regex" on Google.
Based on the DFA proposed by the author, a ridiculously short regex can be generated by simplifying the routes a binary string can take through the DFA.
The simplest one, using only state A, is:
0*
Including state B:
0*(11)*0*
Including state C:
0*(1(01*0)*1)*0*
And include the fact that after going back to state A, the whole process can be started again.
0*((1(01*0)*1)*0*)*
Using some basic regex rules, this simplifies to
(1(01*0)*1|0)*
Have a nice day.
If I may plug my solution for this code golf question! It's a piece of JavaScript that generates regexes (probably inefficiently, but does the job) for divisibility for each base.
This is what it generates for divisibility by 3 in base 2:
/^((((0+)?1)(10*1)*0)(0(10*1)*0|1)*(0(10*1)*(1(0+)?))|(((0+)?1)(10*1)*(1(0+)?)|(0(0+)?)))$/
Edit: comparing to Asmor's, probably very inefficient :)
Edit 2: Also, this is a duplicate of this question.
For some who is learning and searching how to do this:
see this video:
https://www.youtube.com/watch?v=SmT1DXLl3f4&t=138s
write state quations and solve them with Axden's Theorem
The way I did is visible in the image-result is the same as pointed out by user #Kert Ojasoo. I hope i did it corretly because i spent 2 days to solve it...
n+2n = 3n. Thus, 2 adjacent bits set to 1 denote a multiple of 3. If there are an odd number of adjacent 1s, that would not be 3.
So I'd propose this regex:
(0*(11)?)+
I have been struggling to find an answer or develop a solution. I am trying to figure out how to make code that makes code in Clojure. For my first feat, I want a function that will print to stdout the name of the symbol and its value, useful for debugging. Example:
(def mysymbol 5)
(debugging-function mysymbol)
mysymbol: 5
Does that make sense? Thanks for your help.
Post Discussion Update
Here is the answer from #amalloy:
(defmacro ?
"A useful debugging tool when you can't figure out what's going on:
wrap a form with ?, and the form will be printed alongside
its result. The result will still be passed along."
[val]
`(let [x# ~val]
(prn '~val '~'is x#)
x#))
So:
(? myvariable)
You can see a simple version of this that I wrote on github. The main point is that you can't do this with a function, but with a macro it's simple enough - you just have to get your quoting and unquoting right.
Given a string, I want to replace all links within it with the link's description. For example, given
this is a [[http://link][description]]
I would like to return
this is a description
I used re-builder to construct this regexp for a link:
\\[\\[[^\\[]+\\]\\[[^\\[]+\\]\\]
This is my function:
(defun flatten-string-with-links (string)
(replace-regexp-in-string "\\[\\[[^\\[]+\\]\\[[^\\[]+\\]\\]"
(lambda(s) (nth 2 (split-string s "[\]\[]+"))) string))
Instead of replacing the entire regexp sequence, it only replaces the trailing "]]". This is what it produces:
this is a [[http://link][descriptiondescription
I don't understand what's going wrong. Any help would be much appreciated.
UPDATE: I've improved the regex for the link. It's irrelevant to the question but if someone's gonna copy it they may as well get the better version.
Your problem is that split-string is clobbering the match data, which
replace-regexp-in-string is relying on being unchanged, since it is going to
go use that match data to decide which sections of the string to cut out. This
is arguably a doc bug in that replace-regexp-in-string does not mention that
your replacement function must preserve the match data.
You can work around by using save-match-data, which is a macro provided for
exactly this purpose:
(defun flatten-string-with-links (string)
(replace-regexp-in-string "\\[\\[[a-zA-Z:%#/\.]+\\]\\[[a-zA-Z:%#/\.]+\\]\\]"
(lambda (s) (save-match-data
(nth 2 (split-string s "[\]\[]+")))) string))