Common Lisp unbound variable / defmacro - variables

I need to make the function defmacro for my meta-circular interpreter that can read this syntax:
pseudoscheme> (defmacro (minus x y) (list ‘- y x))
MINUS
pseudoscheme> (expand-macro '(minus 3 2))
(- 3 2)
When I use this:
(defmacro my-defmacro ((name &rest args) &body body)
(let ((form (gensym))(env (gensym)))
(progn
`(setf (macro-function ',name)
(lambda (,form ,env))
(destructuring-bind ,args (rest, form) ,#body))
name
)
)
)
and then:
(my-defmacro (min a b)(list '- a b))
I get this error:
Error: The variable MIN is unbound.
I can't understand why.
-----EDITED-----
If I use this:
(defmacro my-defmacro ((name &rest args) &body body)
(let ((form (gensym))(env (gensym)))
`(progn (setf (macro-function ',name)
(lambda (,form ,env))
(destructuring-bind ,args (rest, form) ,#body))
',name)
)
)
and then:
(my-defmacro (min a b)(list '- a b))
I get this error:
Error: Odd number of args to SETF: ((MACRO-FUNCTION (QUOTE PLUS)) (LAMBDA (#:G786 #:G787)) (DESTRUCTURING-BIND (A B) (REST #:G786) (LIST # A B)))

Your my-defmacro works for you host CL system, but I get the feeling you want macro capabilities in your interpreter and this won't do it. (except if ythe interpreter environment is the global host implementations environment, but that would make a lot of challenges)
I don't know how you do compound procedures in your evaluator but when my evaluator gets a (lambda (x) (+ x x)) it is turned into (compound-procedure <env> (x) (+ x x)). My macros turn into almost the same except the first element is compound-syntax.
Every evaluated operator has a tag which tells it what it is (one of primitive-syntax, primitive-procedure, compound-syntax, compound-procedure) and I only need a general way of dealing with those 4.
The real difference between a compound procedure and compound syntax is that the arguments gets evaluated for a procedure and in a compound syntax the result gets evaluated.
So. Have you implemented so that ((lambda (x) (+ x x)) 5) works? Well, then you'll almost implemented macros as well. This is of course not true for a compiler, since this approach would expand the code every time it's run instead of expanding once when the closure gets created. (Optimizations is no way to go on the first version anyway)

For your 'edited code' you have a misplaced paren:
(defmacro my-defmacro ((name &rest args) &body body)
(let ((form (gensym))(env (gensym)))
`(progn (setf (macro-function ',name)
(lambda (,form ,env)) ;; <== HERE
(destructuring-bind ,args (rest, form) ,#body))
',name)
)
)
which leads to setf having three subforms. Rewrite it like this (while using standard Lisp formatting):
(defmacro my-defmacro ((name &rest args) &body body)
(let ((form (gensym))
(env (gensym)))
`(progn (setf (macro-function ',name)
(lambda (,form ,env)
(destructuring-bind ,args (rest, form)
,#body)))
',name)))

Related

scheme - dynamic scope - why this is the return value?

why under dynamic scope this code will return error for "g not defined"?
when running ((ff) 5), at some point g will get a value (the f lambda) and will be inserted into the runtime stack.
(
let ((f (lambda (g)
(lambda (n)
(if (zero? n)
1
(* n ((g g) (- n 1))))))))
((f f) 5)
)
With dynamic scope you don't have closures. Eg.
(define val #f)
(define (get-val val)
(lambda ()
val))
(define getter (get-val 5))
(getter) ; => #f
With lexical scope val from get-val lives in the returned procedure as a free variable and would return 5, but in dynamic scope it stopped existing right ather the proceudre was returned. The val referred in the procedure is whatever bound val in the dynamic scope. Eg.
(let ((val 10))
(getter)) ; ==> 10
So val from the let became the closest binding with that name ad getter returned that.

Processing SQL Queries as Lazy Streams in Racket

Language: Racket (with SQL query code/pointer)
Libraries: db, racket/stream, racket/sequence
Goal: lazily process the value of sql queries using streams in Racket.
Question 1: how do you manipulate SQL query stream objects in Racket? (I can get the stream-first value of the stream but not the rest of the stream!)
#lang racket/base
(require db
racket/sequence
racket/stream)
(define db_sql_local
(mysql-connect
#:user "<my-username>"
#:database "<my-database>"
#:server "<my-server>"
#:port <my-port>
#:password "<my-password>"))
;; PROBLEM 1 HERE
(define test-stream
(sequence->stream
(in-query
chembl_sql_local
"SELECT * FROM <table-name>"
#:fetch +inf.0)))
(stream-first test-stream)
;; stream-first of test-stream returns the first-row of the table as a '(#vector).
Any advice or comments would be greatly appreciated - Thank you!
First, the sequence returned by in-query does not contain vectors; each "element" of the sequence contains multiple values, one per column returned. See the paragraph in the Sequence docs starting "Individual elements of a sequence..." about multiple-valued elements.
Second, using #:fetch +inf.0 (the default behavior) means that all rows are fetched before the sequence is returned. So there's nothing lazy about the code above; you could use query-rows instead and get a list, which would be easier to work with (and query-rows does represent each row as a vector).
Finally, use stream-rest to get the rest of a stream. For example:
(require db racket/stream racket/sequence)
(define c (sqlite3-connect #:database 'memory))
(define qseq (in-query c "SELECT 1, 2 UNION SELECT 3, 4" #:fetch 1))
qseq
;; => #<sequence>
(define qstream (sequence->stream qseq))
qstream
;; => #<stream>
(stream-first qstream)
;; => 1 2
(stream-rest qstream)
;; => #<stream>
(stream-first (stream-rest qstream))
;; => 3 4
thanks for your quick reply. The #:fetch 1 arg was definitely what I was looking for to make it lazy. I've attached updated code that should lazily stream sql queries to export tsv files.
(define sql_server
(mysql-connect
#:user <username>
#:database <db-name>
#:server <server>
#:port <port-num>
#:password <password>))
(define query-->stream
(lambda (db-conn query)
(sequence->stream
(in-query
db-conn
query
#:fetch 1))))
(define print-table-row-to-tsv
(lambda (ls port)
(cond
((null? ls)
(fprintf port "~c" #\newline)
(void))
((sql-null? (car ls))
(fprintf port "~a~c" "NULL" #\tab)
(print-table-row-to-tsv (cdr ls) port))
((null? (cdr ls))
(fprintf port "~a" (car ls))
(print-table-row-to-tsv (cdr ls) port))
(else
(fprintf port "~a~c" (car ls) #\tab)
(print-table-row-to-tsv (cdr ls) port)))))
(define get-table-col-names
(lambda (db-conn tbl-name)
(map (lambda (x) (vector-ref x 0))
(query-rows db-conn (string-append "DESCRIBE " tbl-name)))))
(define export-query-result-to-tsv
(lambda (db-conn tbl-name query)
(let* ((tbl-col-names (get-table-col-names db-conn tbl-name))
(output-file (open-output-file (format "~achembl_~a_table.tsv" (find-system-path 'home-dir) tbl-name) #:exists 'replace))
(stream (query-->stream db-conn query)))
(begin
(print-table-row-to-tsv tbl-col-names output-file)
(process-stream-to-tsv stream output-file)
(close-output-port output-file)))))
(define process-stream-to-tsv
(lambda (stream port)
(cond
((stream-empty? stream)
(void))
(else
(begin
(print-table-row-to-tsv (call-with-values (lambda () (stream-first stream)) list) port)
(process-stream-to-tsv (stream-rest stream) port))))))
(export-query-result-to-tsv sql_server "<table-name>" "SELECT * FROM <table-name>;")

CLOS: Format initialization argument list for make-instance

I've been scratching my head on this for a while now - maybe someone could shed some light on how to format an initialization argument list for 'make-instance' from a nested list containing (key value) sublists. Example:
(make-instance 'myclass :initarg1 1 :initarg2 2 :initarg3 '(a b))
If I have the keywords and values in a list like so:
'((initarg1 1) (initarg2 2) (initarg3 '(a b)))
Any help and pointers appreciated!
Thanks,
Marleynoe
(apply #'make-instance 'myclass
(loop for (parameter value) in '((initarg1 1) (initarg2 2) (initarg3 '(a b)))
collect (intern (symbol-name parameter) (find-package :keyword))
collect value))
(apply #'make-instance 'myclass
(mapcan #'(lambda (param)
(list (intern (symbol-name (car param)) (find-package :keyword))
(cadr param)))
'((initarg1 1) (initarg2 2) (initarg3 '(a b)))))
The idea is that each (initargk k) parameter pair is mapped to a fresh list (:initargk k) and then all of them are concatenated in order together. This is a typical pattern for the map function mapcan.

Scheme - using `this` as argument of a lambda function?

Could someone please clarify the concepts behind this use of the "this" keyword?
(define call
(lambda (obj method-name . args)
(apply (obj method-name) obj args)))
(define -cuboid-
(lambda (w l h)
(define volume
(lambda (this)
(* h (call this 'area))))
(define area
(lambda (this)
(* w l)))
(lambda (method-name)
(cond
((eq? 'volume method-name) volume)
((eq? 'area method-name) area)
(else (error "method not found: ~s" method-name))))
(define r1 (-cuboid- 2 3 4))
(call r1 'area) ;=> 6
(call r1 'volume) ;=> 24
I understand that this is a keyword to refer to the object that is being used. I found out that this alone doesn't have any particular meaning in this program (it needs to refer to the arguments of the lambda functions).
The call is ((-cuboid- 2 3 4) 'volume), which brings to (* h (call this 'area)), where has this been defined?
this is simply the argument of the lambda, this could be anything; try changing it to, e.g., myself in the first lambda and me in the second (where it is not used, by the way, but needs to be there for the call to work).
The call to ((-cuboid- 2 3 4) 'volume) returns that procedure, with names bound according to the sketch below:
In call, r1 'volume calls the "lookup method" of -cuboid- and returns the volume procedure, which is then called with the obj argument, binding that to the name this
Thus, this gets bound to the r1 argument to call

Binding multiple definitions to one "variable" in scheme?

I think I read somewhere that you could bind multiple definitions to a single name in scheme. I know I might be using the terminology incorrectly. By this I mean it is possible to do the following (which would be really handy to defining an operator)?
I believe I read something like this (I know this is not real syntax)
(let ()
define operator "+"
define operator "-"
define operator "*"
define operator "/"))
I want to test another variable against every operator.
I'm not really sure what you're asking. Do you want a single procedure that can handle different types of arguments?
(define (super-add arg1 arg2)
(cond ((and (string? arg1) (string? arg2))
(string-append arg1 arg2))
((and (number? arg1) (number? arg2))
(+ arg1 arg2))
(else
(error "UNKNOWN TYPE -- SUPER-ADD"))))
(super-add "a" "b") => "ab"
(super-add 2 2) => 4
Are you interested in message passing?
(define (math-ops msg) ;<---- returns a procedure depending on the msg
(cond ((eq? msg 'add) +)
((eq? msg 'sub) -)
((eq? msg 'div) /)
((eq? msg 'multi) *)
(else
(error "UNKNOWN MSG -- math-ops"))))
((math-ops 'add) 2 2) => 4
((math-ops 'sub) 2 2) => 0
Also the proper syntax for a let binding:
(let (([symbol] [value])
([symbol] [value]))
([body]))
(let ((a 2)
(b (* 3 3)))
(+ a b))
=> 11
It will be very hard to help more than this without you clarifying what it is you are trying to do.
EDIT: After your comment, I have a little bit better of an idea for what you're looking for. There is not way to bind multiple values to the same name in the way that you mean. You are looking for a predicate that will tell you whether the thing you are looking at is one of your operators. From your comment it looked like you will be taking in a string, so that's what this is based on:
(define (operator? x)
(or (string=? "+" x) (string=? "-" x) (string=? "*" x) (string=? "/" x)))
If you are taking in a single string then you will need to split it into smaller parts. Racket has a built in procedure regexp-split that will do this for you.
(define str-lst (regexp-split #rx" +" [input str]))
You may be referring to the values construct, which "delivers arguments to a continuation". It can be used to return multiple values from a function. For example,
(define (addsub x y)
(values (+ x y) (- x y)))
(call-with-values
(lambda () (addsub 33 12))
(lambda (sum difference)
(display "33 + 12 = ") (display sum) (newline)
(display "33 - 12 = ") (display difference) (newline)))