eval a list into a let on clojure - binding

My problem is the next, i try to evaluate a list with some vars using a let to asign values to this vars
if i do (def a (list * 'x 'y)) and (let [x 3 y 3] (eval a)) I have a
CompilerException java.lang.RuntimeException: Unable to resolve symbol: x in this context, compiling:(NO_SOURCE_PATH:6)
but if I run
(def x 4) (def y 4) and (eval a) i have a 16, anyway if I run again (let [x 3 y 3] (eval a)) again I have 16,
exist a method to binding the x and y correctly and eval the list?
ty!

let defines lexically scoped bindings that are not accessible from the body of the eval function. This is no different than any other function. However, the bindings created with def are accessible because they are namespace global. All functions have access to namespace global variables, as long as they are public.

(def ^:dynamic x 4) (def ^:dynamic y 4)
user=> (binding [x 3 y 3] (eval a))
9
user=> (eval a)
16

Well, you could also eval the let expression, See if this is what you need:
(eval '(let [x 3 y 3] (* x y)))
EDIT :
According to the comments, this will work for your case:
(def a (list (list * 'x 'y)))
(eval (concat '(let [x 3 y 3]) a))
Even better, use quasiquoting:
(def a (list * 'x 'y))
(eval `(let ~'[x 3 y 3] ~a))

Related

Racket: How can I fix my code so that it will return all the flipped pairs that is missing?

This function should return the symmetric closure of L.
Examples:
(Symmetric-Closure'((a a) (a b) (b a) (b c) (c b))) ---> '((a a) (a b) (b a) (b c) (c b))
(Symmetric-Closure'((a a) (a b) (a c))) ---> '((a a) (a b) (a c) (b a)(c a))
(Symmetric-Closure'((a a) (b b))) ---> '((a a) (b b))
(Symmetric-Closure'())---> '()
Here is what I have in Racket
(define (Symmetric-Closure L)
;Iterate over each pair in L
(andmap (lambda (x)
;If the flipped pair does not exist in L, it will
;return L and the flipped pair that is missing. Otherwise, return L.
(if(not(member (list (cadr x)(car x)) L))
(cons (list (cadr x)(car x)) L)
(append L)))
L))
How can I fix my code so that it will return all the flipped pairs that is missing
For example, my code only return L and the last missing flipped pair (c a) instead of (b a) and (c a)
;this is wrong, it should return '((c a)(b a)(a a)(a b)(a c))
(Symmetric-Closure '((a a)(a b)(a c))-----> '((c a)(a a)(a b)(a c))
;this is correct
(Symmetric-Closure '((a a)(a b)(b a)(b c)(c b)))-----> '((a a)(a b)(b a)(b c)(c b))
andmap means "map the list using this function and then and together the results." In Racket, whenever you and together any values, the result is going to be either the last value provided to it, or false. For example, (and value1 value2) results in value2 if neither value1 nor value2 is false (and if one of them is false, the result is false as well). Since the value produced by your lambda is never false, the result of your andmap is going to be the value of the lambda expression the final time it is called, which in this case, could be the list (cons (list (cadr x)(car x)) L) for the last value of x that it sees in the original list L. This means that all preceding values that were consed don't factor into the result at all.
You could modify this to use a simple map instead. But this produces a list of lists of pairs, not a list of pairs which is what you want. So at the end you need to flatten this to arrive at the result.
(define (symmetric-closure L)
;Iterate over each pair in L
(apply append
(map (lambda (x)
;If the flipped pair does not exist in L, it will
;return L and the flipped pair that is missing. Otherwise, return L.
(if (not (member (list (cadr x) (car x)) L))
(list (list (cadr x) (car x)) x)
(list x)))
L)))
One thing to be aware of, though, is that this algorithm calls member for every element in the original list. Checking for membership in a list is O(N) and you are doing this N times, meaning that the complexity of this algorithm is O(N²). You should be able to do this more efficiently, for instance by using a hash set.

How to make an infinite stream of x and sin(x) in scheme?

i would like to make an infinite stream (x, f(x), f(f(x),f(f(f(x))),...) and the procedure should take x as an value and f as an procedure. I tried the following code but i don't know if it is true... how can i improve my code?
(define (f_stream x f) (cons-stream x (f_stream (f x) (lambda (x)
(sin x)) (f x)))) (sin x)) (f x))))
(define (f x) (sin x))
What did you is close, but you put extra stuff about 'sin' into it while it should be generic. All you needed was this:
(define (f_stream x f) (cons-stream x (f_stream (f x) f)))
notice f is passed as a function instead of using lambda.

delete! function for R5RS

I'm trying to write a delete! function that mutates a list and removes from it a specified value. This is the code I have so far.
(define (extend! l . xs)
(if (null? (cdr l))
(set-cdr! l xs)
(apply extend! (cdr l) xs)))
(define (delete! lis y)
(define returnLis '())
(for-each (lambda(x) (if(not(eq? x y))
(extend! returnLis x))) lis)
returnLis)
The problem I am having is that I am trying to add to an empty list which can't be done in Scheme.
Desired outcome:
(delete! '(1 2 3 4 5) 3)
=> (1 2 4 5)
Your extend function use actually would make a copy of each element in a fresh pair, but since the initial value is '() it cannot be set-cdr!. The whole point of mutating something is that old variables will continue point to the changed data and making a copy won't do that.
You need to see the pairs. You want to remove 3
[1,-]->[2,-]->[3,-]->[4,-]->[5,-]->()
So When you have found 3, you need to change the cdr of the pair that holds 2 and pint it the pair that holds 3s cdr like this:
[1,-]->[2,-]->[4,-]->[5,-]->()
Something like this then:
(define (delete lst e)
(if (and (not (null? lst)) (not (null? (cdr lst))))
(if (equal? (cadr lst) e)
(set-cdr! lst (cddr lst))
(delete (cdr lst) e))
'undefined))
(define test (list 1 2 3 4 5))
(delete lst 3)
lst ; ==> (1 2 4 5)
Notice I'm using list since a quoted literal cannot be used here since you are not allowed to change constant data like '(1 2 3 4 5). The result will be undefined or it will signal an error.
It won't work if the element in question is the first. It's because the variable points to the first pair and this only changes the pointers in pairs, not bindings. One could just switch the two first and delete the second, but in the event you have a one element list you are still stuck. Scheme implementations of mutable queues usually have a head consisting of a dummy element not considered part of the list to delete the first element.
All you need is a head-sentinel technique:
(define (delete! lis y)
(define returnLis (list 1))
(for-each (lambda(x) (if(not(eq? x y))
(extend! returnLis x))) lis)
(cdr returnLis))
Well, not all... because as it is, this is a quadratic algorithm. It re-searches the returnLis from top anew while adding each new element with extend!. Better just maintain the last cdr cell and update it:
(define (delete! lis y)
(define returnLis (list 1))
(define last-cell returnLis)
(for-each (lambda(x) (cond ((not(eq? x y))
; (extend! last-cell x)
(set-cdr! last-cell (list x))
(set! last-cell (cdr last-cell)))))
lis)
(cdr returnLis))
But, as #Sylwester points out, with this approach you shouldn't use an exclamation mark in the name, as this will return a freshly built list instead of mutating the argument's structure.

Scheme: pattern matching syntax

This was an edit to an earlier post. I am reposting it because I think the original isn't getting any more views since I accepted a partial answer already.
I have written a function match-rewriter which is just match-lambda except that it returns its argument if no match is found.
Using match rewriter I want to be able to write rules that can be passed to another function rewrite which is this:
#| (rewrite rule s) repeatedly calls unary function 'rule' on every "part"
of s-expr s, in unspecified order, replacing each part with result of rule,
until calling rule makes no more changes to any part.
Parts are s, elements of s, and (recursively) parts of the elements of s. (define (rewrite rule s) |#
(let* ([with-subparts-rewritten
(if (list? s) (map (λ (element) (rewrite rule element)) s) s)]
[with-also-rule-self (rule with-subparts-rewritten)])
(if (equal? with-also-rule-self with-subparts-rewritten)
with-also-rule-self
(rewrite rule with-also-rule-self))))
Here is an example of proper usage:
(define arithmetic
(match-rewriter (`(+ ,a ,b) (+ a b))
(`(* ,a ,b) (* a b))
))
(rewrite arithmetic '(+ (* 2 (+ 3 4)) 5))
==>
19
Now I have written:
(define let→λ&call
(match-rewriter (`(let ((,<var> ,<val>) . (,<vars> ,<vals>)) ,<expr> . ,<exprs>)
`((λ (,<var> . ,<vars>) ,<expr> . ,<exprs>) ,<val> . ,<vals>))))
to implement lets as lambda calls, but this is how it is behaving:
(rewrite let→λ&call '(let((x 1) (y 2) (z 3)) (displayln x) (displayln y) (displayln z)))
'((λ (x y 2)
(displayln x)
(displayln y)
(displayln z))
1
z
3)
which, I have to say, really has me stumped. Strangely this call:
(rewrite let→λ&call '(let((w 0) (x 1) (y 2) (z 3)) (displayln w) (displayln x) (displayln y) (displayln z)))
'(let ((w 0) (x 1) (y 2) (z 3))
(displayln w)
(displayln x)
(displayln y)
(displayln z))
Just returns its argument, meaning that match-rewriter did not find a match for this pattern.
Any advice is appreciated.
Thanks.
This pattern:
((,<var> ,<val>) . (,<vars> ,<vals>))
does not do what you want. In particular, it's equivalent to:
((,<var> ,<val>) ,<vars> ,<vals>)
I recommend that you use regular match patterns, rather than quasi-patterns, until you have a better sense of how they work. The pattern for this would be:
(list (list <var> <val>) (list <vars> <vals>) ...)

Symbolic mathematical calculations in Clojure vs. F#

I have come across the following F# sample and found it intriguing.
http://www.codeproject.com/KB/net-languages/SymbolicCalcInFS.aspx
Does Clojure have language/library facilities for doing something like this with ease? It is ok to force Polish notation for formulas, if that makes things easier.
Thanks, and let me know if there are questions.
Lisp has long history in symbolic computing. See the AI case study book by Peter Norvig. Lisp provides a lot of great language features to abstract the common operations on the symbols. Sometimes you can write really concise code (more concise/short than F#).
Static languages like F# have strong type systems and convenient pattern matching on the data types. The compiler could find errors that are caught by the type system, e.g. lack of considering one special case. Thinking about types with your data could also reduce the chances for runtime error. The type inference in F# also makes F# code very concise.
I don't know much about Clojure, but here are, at least, some pointers.
The key feature that makes the F# code nice is pattern matching on algebraic data types. An algebraic data type is for example the declaration of the Expression type (that is used to represent mathematical expressions) and pattern matching is the match construct that is used to check for various known cases when implementing simplification or differentiation.
I don't think that Clojure has any built-in support for pattern matching, but it can be implemented as a library. One library that looks quite interesting is the patter-match module (in Clojars). Here is an example that uses it to implement algebraic evaluator (which is quite close to the F# article).
Another thing that appears in the F# article is active patterns (which allow you to declare and reuse patterns). I don't think that there is a Clojure library for that, but given the flexibility of the language, it should be possible to implement them too (however, they are not really that necessary in the F# article)
Symbolic differentiation was one of the first applications of lisp!
I made a blogpost about a simple symbolic differentiator. It only deals with + and *, but it is easily extended.
It was part of a series I wrote to introduce beginners to clojure at a conference in London, to show how easy it is for clojure to manipulate its own code.
Of course the cute thing is that having done the differentiation, the code can then be compiled! So you can produce differentiated versions of user input, or macros that produce functions and their derivatives, etc.
The original's here, and nicely syntax highlighted:
http://www.learningclojure.com/2010/02/clojure-dojo-4-symbolic-differentiation.html
But I've posted the code here so you can have a look:
;; The simplest possible symbolic differentiator
;; Functions to create and unpack additions like (+ 1 2)
(defn make-add [ a b ] (list '+ a b))
(defn addition? [x] (and (=(count x) 3) (= (first x) '+)))
(defn add1 [x] (second x))
(defn add2 [x] (second (rest x)))
;; Similar for multiplications (* 1 2)
(defn make-mul [ a b ] (list '* a b))
(defn multiplication? [x] (and (=(count x) 3) (= (first x) '*)))
(defn mul1 [x] (second x))
(defn mul2 [x] (second (rest x)))
;; Differentiation.
(defn deriv [exp var]
(cond (number? exp) 0 ;; d/dx c -> 0
(symbol? exp) (if (= exp var) 1 0) ;; d/dx x -> 1, d/dx y -> 0
(addition? exp) (make-add (deriv (add1 exp) var) (deriv (add2 exp) var)) ;; d/dx a+b -> d/dx a + d/dx b
(multiplication? exp) (make-add (make-mul (deriv (mul1 exp) var) (mul2 exp)) ;; d/dx a*b -> d/dx a * b + a * d/dx b
(make-mul (mul1 exp) (deriv (mul2 exp) var)))
:else :error))
;;an example of use: create the function x -> x^3 + 2x^2 + 1 and its derivative
(def poly '(+ (+ (* x (* x x)) (* 2 (* x x))) 1))
(defn poly->fnform [poly] (list 'fn '[x] poly))
(def polyfn (eval (poly->fnform poly)))
(def dpolyfn (eval (poly->fnform (deriv poly 'x))))
;;tests
(use 'clojure.test)
(deftest deriv-test
(testing "binary operators"
(is (= (let [m '(* a b)] [(multiplication? m) (make-mul (mul1 m) (mul2 m))]) [true '(* a b)]))
(is (= (let [m '(* a b)] [(addition? m) (make-add (add1 m) (add2 m))]) [false '(+ a b)])))
(testing "derivative function"
(is (= (deriv '0 'x) '0))
(is (= (deriv '1 'x) '0))
(is (= (deriv 'x 'x) '1))
(is (= (deriv 'y 'x) '0))
(is (= (deriv '(+ x x) 'x) '(+ 1 1)))
(is (= (deriv '(* x x) 'x) '(+ (* 1 x) (* x 1))))
(is (= (deriv '(* x x) 'y) '(+ (* 0 x) (* x 0))))
(is (= (deriv '(* x (* x x)) 'x) '(+ (* 1 (* x x)) (* x (+ (* 1 x) (* x 1)))))))
(testing "function creation: d/dx (x^3 + 2x^2 + 1) = 3x^2 + 4x "
(let [poly '(+ (+ (* x (* x x)) (* 2 (* x x))) 1)]
(is (= ((eval (poly->fnform poly)) 3) 46))
(is (= ((eval (poly->fnform (deriv poly 'x))) 3))))))
I haven't tried it, but Clojuratica looks very interesting.
Well, now Clojure offer powerful pattern matching libraries :
matchure : https://github.com/dcolthorp/matchure
match : https://github.com/swannodette/match
Yes, a system such as you describe now exists on Clojure! It is none other than Gerry Sussman's companion system to his -and Wisdom's- SICM (Structure and Interpretation of Classical Mechanics) book. For Clojure it's been named sicmutils, and ported by Colin Smith.
I've described it briefly elsewhere - https://stackoverflow.com/a/41646455/4070712 - but in short yes, it definitely does the four things you F# article mentions, viz.
Differentiation:
Simplification of algebraic expressions
Formatting
Parsing of expressions
and much, much more...
1) Differentiation (full partial differentiation supported)
> (defn ff [x y] (* (expt x 3)(expt y 5)))
> ((D ff) 'x 'y) ==> (down (* 3 (expt x 2) (expt y 5)) (* 5 (expt x 3) (expt y 4)))
> ;; i.e. vector of results wrt to both variables
NB. Two types of vectors are supported, "up" and "down" to accomodate covariant and contravariant expressions
2) Simplification of expressions: Oh, yes...
> (def unity (+ (square sin) (square cos)))
> (unity 'x) ==> 1 ;; yes we can deal with symbols
3) Formatting: Expressions can be rendered in TeX for beautiful display.
I can't show this easily here, but currently a Maple-style notebook/workshhet is under development, using Clojure's "Gorilla"
4) Parsing: Obviously. Converting between expressions and functions is a core part of the system.
Have a look at https://github.com/littleredcomputer/sicmutils . you don't even need Clojure to run it, you can use the supplied Java jar file.

Resources