Clojure: quote vs syntax quote evaluation order - clojure

I'm trying to understand quoting in clojure and came across this article. While trying out the examples, I'm confused about the order of evaluation of quoting expressions.
`(~`'baz)
;; ↪ ('user/baz)
`(~'`baz)
;; ↪ ('user/baz)
Why do both the above expressions evaluate to ('user/baz)? Shouldn't the first one evaluate to ('baz)?

Putting an explanation into a code block because backticks mess up the formatting. Note that I don't use strict Clojure, mixing inputs with outputs, because it's easier to explain that way, at least for me.
`'bar and '`bar are the same because:
- 'bar is (quote bar)
> `(quote bar) is (`quote `bar) which is (quote user/bar)
- `bar is user/bar
> 'user/bar is (quote user/bar)

Related

Regex to extract S expression?

I'm wondering if it's possible to do a pass on parsing of a define expression in lisp with a single regular expression, for example with the following input:
#lang sicp
(define (square x) (* x x))
(define (average x y) (/ (+ x y) 2))
; using block scope
(define (sqrt x)
; x is always the same -- "4" or whatever we pass to it, so we don't need that
; in every single function that we define, we can just inherit it from above.
(define (improve guess) (average guess (/ x guess)))
(define (good-enough? guess) (< (abs (- (square guess) x)) 0.001 ))
(define (sqrt-iter guess) (if (good-enough? guess) guess (sqrt-iter (improve guess))))
(sqrt-iter 1.0)
)
(sqrt 4)
I would want to highlight the three procedures below (none of the function-scoped procedures) that start with define. The process I was thinking (if I were to do it iteratively) would be:
Remove comments.
Grab the start of the define with \(\s*define
Consume balanced parentheses up until the unbalanced ) that finishes our procedure. For a regex, something like: (?:\([^)]*\))*, though I'm sure it gets much more complex with the greediness of the *'s.
And this wouldn't even be taking into account I could have a string "( define )" that we'd also want to ignore.
Would it be possible to build a regex for this, or too complicated? Here is my starting point, which is a long way from complete: https://regex101.com/r/MlPmOd/1.
As a preface, there is a famous quote due to Jamie Zawinski:
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
The one word answer to your question is 'no'. Regular languages – the languages that regular expressions can recognise – are a proper subset of context-free languages, and the written form of s-expressions is context-free but not regular. So no regular expression can recognise the written form of an s-expression.
To see this consider a very tiny subset of s-expressions:
n = () | ( n)
So n consists of the set {(), (()), ((())), ...}, where the number of left parens and right parens in each string are equal. Such a language can't be recognised by a regular expression because you need to count parens.
Notes
Some instances of what are called 'regular expressions' in various programming languages are in fact more powerful than regular expressions and can therefore recognise classes of languages larger than regular languages. jwz's quote still applies: just because, perhaps, you can does not mean you should.
All programmers should in my opinion learn enough formal language theory to be dangerous. I don't know what a good modern reference is, but I learnt it from the Cinderella book: Hopcroft & Ullman, Introduction to Automata Theory, Languages, and Computation.
All Lisp programmers should in my opinion write a toy reader for s-expressions, as this is a good way of learning about how the real reader works, and doesn't take long.

What does a quote mean in front of a vector in clojure?

Suppose you have the following line of code in clojure. What do you need the quote for?
(require '[clojure.string :as str])
A quote prevents evaluation. By default, all expressions are evaluated in Clojure. Using a quote in front of the expression prevents the evaluation. Most expressions in Clojure are self-evaluating (they evaluate to themselves). The two main exceptions are symbols and lists. Edit: See comment from #amalloy below and response.
In this case, the quote is creating a literal vector whose first element is the symbol clojure.string, the second element is the keyword :as and the third is the symbol str.
Without the quote, (require [clojure.string :as str]), would try to evaluate the symbols clojure.string and str and the value would be whatever the var bound to those symbols contains (or an error, if there is nothing bound).
Here is an example demonstrating the difference. Let's say you have the following two defs.
(def a 16)
(def b 12)
Now, '[a 14 b] would evaluate to the vector [a 14 b]. But, [a 14 b] would evaluate to [16 14 12].
See the Evaluation section on clojure.org for the details on exactly how a symbol is resolved in Clojure.
You might also find the documentation for quote to be helpful, as also the section on Clojure syntax.

Eval with local bindings function

I'm trying to write a function which takes a sequence of bindings and an expression and returns the result.
The sequence of bindings are formatted thus: ([:bind-type [bind-vec] ... ) where bind-type is either let or letfn. For example:
([:let [a 10 b 20]] [:letfn [(foo [x] (inc x))]] ... )
And the expression just a regular Clojure expression e.g. (foo (+ a b)) so together this example pair of inputs would yeild 31.
Currently I have this:
(defn wrap-bindings
[[[bind-type bind-vec :as binding] & rest] expr]
(if binding
(let [bind-op (case bind-type :let 'let* :letfn 'letfn*)]
`(~bind-op ~bind-vec ~(wrap-bindings rest expr)))
expr))
(defn eval-with-bindings
([bindings expr]
(eval (wrap-bindings bindings expr))))
I am not very experienced with Clojure and have been told that use of eval is generally bad practice. I do not believe that I can write this as a macro since the bindings and expression may only be given at run-time, so what I am asking is: is there a more idiomatic way of doing this?
eval is almost always not the answer though sometimes rare things happen. In this case you meet the criteria because:
since the bindings and expression may only be given at run-time
You desire arbitrary code to be input and run while the program is going
The binding forms to be used can take any data as it's input, even data from elsewhere in the program
So your existing example using eval is appropriate given the contraints of the question at least as I'm understanding it. Perhaps there is room to change the requirements to allow the expressions to be defined in advance and remove the need for eval, though if not then i'd suggest using what you have.

SICP lisp 'if' conditional expression explanation

I'm working through SICP and have gotten to the part about the square root code. I understood that 'if' statements could only be followed by single expressions. However, in the code,
(define (sqrt-iter guess x)
(if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
I don't understand how the 3rd, 4th, and 5th lines are valid when the 'guess' and 'x' have already been stated as the consequent expressions for 'if'.
In some Scheme interpreters an if special form can be followed by one or two expressions after the condition, in others (for example: Racket) the condition must be followed by exactly two expressions. But in your code there are two expressions after the condition! it's more of an indentation problem, see:
(define (sqrt-iter guess x)
(if (good-enough? guess x) ; condition
guess ; first expression (consequent)
(sqrt-iter (improve guess x) ; second expression (alternative)
x)))
To clarify: guess and x are not the consequent and alternative of the condition, they are the arguments for the good-enough? procedure in the expression (good-enough? guess x), which is just the condition part. Remember that the general structure of an if expression looks like this:
(if <condition>
<consequent>
<alternative>)
Where each part is an expression. For further details please refer to the documentation.
guess and x are arguments to the good-enough? predicate, "if" is selecting between the following guess and (sqrt-iter ...) expressions.
No, In scheme language, 'if' statements could followed by two or three expressions, not only one.
(if test-exp then-exp else-exp)
Even in some implement of scheme interpreter,'if' statements MUST followed by three expressions, 'else-exp' can not be ommitted.
More details read:
http://classes.soe.ucsc.edu/cmps112/Spring03/languages/scheme/SchemeTutorialA.html#condexp

Java's Pattern/quote equivalent in ClojureScript

When I am in Clojure, I can use (re-pattern (java.util.regex.Pattern/quote foo)) to exactly match the pattern string with another string. How can I do a similar thing in ClojureScript?
Edit: I also found this - Replicate the functionality of Java's "Pattern.quote" in a JavaScript RegExp
There is no built-in Clojure or Javascript function for this.
This clojure function should escape special regexp characters in a string:
(defn re-quote [s]
(let [special (set ".?*+^$[]\\(){}|")
escfn #(if (special %) (str \\ %) %)]
(apply str (map escfn s))))
http://ideone.com/QXbbB
Disclaimer: I haven't tested this extensively so you may want to get a second opinion before using this code to sanitize potentially evil strings.
I should say first off that I use neither ClojureScript nor Javascript, but a quick search for ClojureScript regex support brought me to this page: https://github.com/clojure/clojurescript/wiki/Differences-from-Clojure, where under the "Other Functions" section, it says: "ClojureScript regular expression support is that of JavaScript", providing this link: http://www.w3schools.com/jsref/jsref_obj_regexp.asp. That next link seems to provide you with what you would be looking for (as a person who doesn't use JavaScript, I am cautious to say for certain).
Edit
Ooh, and maybe the answer to this old question here: Converting user input string to regular expression will give you a more complete answer.