Reversing the function usage in compose function - macros

The compose function applies last function first, i.e. it applies sent functions in reverse order. For example:
((compose sqrt add1) 8)
Above will add1 to 8 and then find sqrt of 9.
I want to create a mycompose function which applies first sent function first, and then second, third etc. Hence, in above example, sqrt needs to be applied first and then add1. I could manage following:
(define (mycompose L arg)
(let loop ((L L)
(res arg))
(cond
[(empty? L) res]
[else (loop (rest L) ((car L) res))])))
(mycompose (list sqrt add1) 8)
I am sure there is a better way. Especially, can above be achieved using macros and also permit multiple arguments to be sent to each function turn by turn?

This “reverse composition” that you describe is often called thrush, and the point-free package provides a thrush function that does precisely what you want. However, let’s say you wanted to implement it yourself. Well, the easiest way would be to reuse the existing implementation of compose, since thrush is just compose with the arguments reversed:
(define (thrush . fs)
(apply compose (reverse fs))
This is, in fact, how the point-free package implements thrush. Still, this might be unsatisfying to you, since you don’t know how compose is implemented. Well, fortunately, we can implement thrush from scratch with a simple fold:
(define (thrush . fs)
(for/fold ([f values])
([g (in-list fs)])
(λ args (call-with-values (thunk (apply f args)) g))))
The real trick here is the use of call-with-values, which properly handles functions that return multiple values. Just like Racket’s compose, this will accept multiple values and pass them along to functions later in the pipeline as multiple arguments, creating a nice symmetry between function inputs and function outputs.

Related

How to express lisp (lambda (pair) (apply #'f pair)) more simply?

Say I've got the following function:
(defun f (v1 v2) ...)
I've got the following code that I'd like to simplify:
(lambda (pair) (apply #'f pair))
The goal here is to create a function that takes a list of two values and calls f with the contents of that list. While this works, it seems a bit verbose. Is there a simpler way to express this?
Maybe:
(lambda(p)(apply #'f p)) ;; 24 bytes
More seriously, Alexandria provides a curry function:
(let ((fun (curry #'apply #'f)))
(funcall fun '(a b)))
Edit: Also, I agree with the sentiment expressed by #Paulo Madeira that your original version is far from being verbose. I would let it as it is, thought, because I think it is in fact easier to debug than using an assert.
(lambda (args) (apply #'f args))
... means "take a list of arguments and apply function F with those arguments". The meaning is straightforward and the function does not make assumptions about what F accepts as arguments. If F is later changed, your closure will still work reliably.
Edit: We don't know what is the context of your code and without more information, your closure looks fishy. If you could describe why you need to pass arguments, we might realize that this approach is not necessarily the most appropriate (or agree that this is in fact a sensible thing to do).

Runtime pattern matching in Racket

If Racket's match macro were a function I could do this:
(define my-clauses (list '[(list '+ x y) (list '+ y x)]
'[_ 42]))
(on-user-input
(λ (user-input)
(define expr (get-form-from-user-input user-input)) ; expr could be '(+ 1 2), for example.
(apply match expr my-clauses)))
I think there are two very different ways to do this. One is to move my-clauses into macro world, and make a macro something like this (doesn't work):
(define my-clauses (list '[(list '+ x y) (list '+ y x)]
'[_ 42]))
(define-syntax-rule (match-clauses expr)
(match expr my-clauses)) ; this is not the way it's done.
; "Macros that work together" discusses this ideas, right? I'll be reading that today.
(on-user-input
(λ (user-input)
(define expr (get-form-from-user-input user-input)) ; expr could be '(+ 1 2), for example.
(match-clauses expr)))
The alternative, which might be better in the end because it would allow me to change my-clauses at runtime, would be to somehow perform the pattern matching at runtime. Is there any way I can use match on runtime values?
In this question Ryan Culpepper says
It's not possible to create a function where the formal parameters and body are given as run-time values (S-expressions) without using eval.
So I guess I'd have to use eval, but the naive way won't work because match is a macro
(eval `(match ,expr ,#my-clauses) (current-namespace))
I got the desired result with the following voodoo from the guide
(define my-clauses '([(list'+ x y) (list '+ y x)]
[_ 42]))
(define-namespace-anchor a)
(define ns (namespace-anchor->namespace a))
(eval `(match '(+ 1 2) ,#my-clauses) ns) ; '(+ 2 1)
Is the pattern matching happening at runtime now? Is it a bad idea?
To answer the first part of your question (assuming you don't necessarily need the match clauses to be supplied at runtime):
The key is to:
Define my-clauses for compile time ("for syntax").
Reference that correctly in the macro template.
So:
(begin-for-syntax
(define my-clauses (list '[(list '+ x y) (list '+ y x)]
'[_ 42])))
(define-syntax (match-clauses stx)
(syntax-case stx ()
[(_ expr) #`(match expr #,#my-clauses)]))
The pattern matching is happening at runtime in the last example.
One way to check is to look at the expansion:
> (syntax->datum
(expand '(eval `(match '(+ 1 2) ,#my-clauses) ns)))
'(#%app eval (#%app list* 'match ''(+ 1 2) my-clauses) ns)
Whether is a good idea...
Using eval is rather slow, so if you call it often it might be better to find another solution. If you haven't seen it already you might want to read "On eval in dynamic languages generally and in Racket specifically." on the Racket blog.
Thank you both very much, your answers gave me much food for thought. What I am trying to do is still not very well defined, but I seem to be learning a lot in the process, so that's good.
The original idea was to make an equation editor that is a hybrid between paredit and a computer algebra system. You enter an initial math s-expression, e.g. (+ x (* 2 y) (^ (- y x) 2). After that the program presents you with a list of step transformations that you would normally make by hand: substitute a variable, distribute, factor, etc. Like a CAS, but one step at a time. Performing a transformation would happen when the user presses the corresponding key combination, although one possibility is to just show a bunch of possible results, and let the user choose the new state of the expression amongst them. For UI charterm will do for now.
At first I thought I would have the transformations be clauses in a match expression, but now I think I'll make them functions that take and return s-expressions. The trouble with choosing compile time vs runtime is that I want the user to be able to add more transformations, and choose his own keybindings. That could mean that they write some code which I require, or they require mine, before the application is compiled, so it doesn't force me to use eval. But it may be best if I give the user a REPL so he has programmatic control of the expression and his interactions with it as well.
Anyway, today I got caught up reading about macros, evaluation contexts and phases. I'm liking racket more and more and I'm still to investigate about making languages... I will switch to tinkering mode now and see if I get some basic form of what I'm describing to work before my head explodes with new ideas.

SICP: Can or be defined in lisp as a syntactic transformation without gensym?

I am trying to solve the last part of question 4.4 of the Structure and Interpretation of computer programming; the task is to implement or as a syntactic transformation. Only elementary syntactic forms are defined; quote, if, begin, cond, define, apply and lambda.
(or a b ... c) is equal to the first true value or false if no value is true.
The way I want to approach it is to transform for example (or a b c) into
(if a a (if b b (if c c false)))
the problem with this is that a, b, and c would be evaluated twice, which could give incorrect results if any of them had side-effects. So I want something like a let
(let ((syma a))
(if syma syma (let ((symb b))
(if symb symb (let ((symc c))
(if (symc symc false)) )) )) )
and this in turn could be implemented via lambda as in Exercise 4.6. The problem now is determining symbols syma, symb and symc; if for example the expression b contains a reference to the variable syma, then the let will destroy the binding. Thus we must have that syma is a symbol not in b or c.
Now we hit a snag; the only way I can see out of this hole is to have symbols that cannot have been in any expression passed to eval. (This includes symbols that might have been passed in by other syntactic transformations).
However because I don't have direct access to the environment at the expression I'm not sure if there is any reasonable way of producing such symbols; I think Common Lisp has the function gensym for this purpose (which would mean sticking state in the metacircular interpreter, endangering any concurrent use).
Am I missing something? Is there a way to implement or without using gensym? I know that Scheme has it's own hygenic macro system, but I haven't grokked how it works and I'm not sure whether it's got a gensym underneath.
I think what you might want to do here is to transform to a syntactic expansion where the evaluation of the various forms aren't nested. You could do this, e.g., by wrapping each form as a lambda function and then the approach that you're using is fine. E.g., you can do turn something like
(or a b c)
into
(let ((l1 (lambda () a))
(l2 (lambda () b))
(l3 (lambda () c)))
(let ((v1 (l1)))
(if v1 v1
(let ((v2 (l2)))
(if v2 v2
(let ((v3 (l3)))
(if v3 v3
false)))))))
(Actually, the evaluation of the lambda function calls are still nested in the ifs and lets, but the definition of the lambda functions are in a location such that calling them in the nested ifs and lets doesn't cause any difficulty with captured bindings.) This doesn't address the issue of how you get the variables l1–l3 and v1–v3, but that doesn't matter so much, none of them are in scope for the bodies of the lambda functions, so you don't need to worry about whether they appear in the body or not. In fact, you can use the same variable for all the results:
(let ((l1 (lambda () a))
(l2 (lambda () b))
(l3 (lambda () c)))
(let ((v (l1)))
(if v v
(let ((v (l2)))
(if v v
(let ((v (l3)))
(if v v
false)))))))
At this point, you're really just doing loop unrolling of a more general form like:
(define (functional-or . functions)
(if (null? functions)
false
(let ((v ((first functions))))
(if v v
(functional-or (rest functions))))))
and the expansion of (or a b c) is simply
(functional-or (lambda () a) (lambda () b) (lambda () c))
This approach is also used in an answer to Why (apply and '(1 2 3)) doesn't work while (and 1 2 3) works in R5RS?. And none of this required any GENSYMing!
In SICP you are given two ways of implementing or. One that handles them as special forms which is trivial and one as derived expressions. I'm unsure if they actually thought you would see this as a problem, but you can do it by implementing gensym or altering variable? and how you make derived variables like this:
;; a unique tag to identify special variables
(define id (vector 'id))
;; a way to make such variable
(define (make-var x)
(list id x))
;; redefine variable? to handle macro-variables
(define (variable? exp)
(or (symbol? exp)
(tagged-list? exp id)))
;; makes combinations so that you don't evaluate
;; every part twice in case of side effects (set!)
(define (or->combination terms)
(if (null? terms)
'false
(let ((tmp (make-var 'tmp)))
(list (make-lambda (list tmp)
(list (make-if tmp
tmp
(or->combination (cdr terms)))))
(car terms)))))
;; My original version
;; This might not be good since it uses backquotes not introduced
;; until chapter 5 and uses features from exercise 4.6
;; Though, might be easier to read for some so I'll leave it.
(define (or->combination terms)
(if (null? terms)
'false
(let ((tmp (make-var 'tmp)))
`(let ((,tmp ,(car terms)))
(if ,tmp
,tmp
,(or->combination (cdr terms)))))))
How it works is that make-var creates a new list every time it is called, even with the same argument. Since it has id as it's first element variable? will identify it as a variable. Since it's a list it will only match in variable lookup with eq? if it is the same list, so several nested or->combination tmp-vars will all be seen as different by lookup-variable-value since (eq? (list) (list)) => #f and special variables being lists they will never shadow any symbol in code.
This is influenced by eiod, by Al Petrofsky, which implements syntax-rules in a similar manner. Unless you look at others implementations as spoilers you should give it a read.

Implenting simultaneous bindings

I'm writing a Lisp (code at GitHub) and I want to implement local bindings. Currently I have two syntaxes:
(let <var> <val> <expr>)
for binding a single variable or function, and
(with (<var1> <val1> ... <varN> <valN>) <expr>)
to bind multiple values at once.
At present, the bindings are evaluated sequentially, and each new function binding retains a copy of the environment it was defined in, so <var2> can refer to <var1> but not vice-versa.
I would like to modify the code so that when binding multiple values at once you effectively have simultaneous binding. For example, I would like to be able to write (this is a trivial example, but it should illustrate the idea):
(define (h y)
(with ((f x) (if (eq? x 0) #t (g (- x 1)))
(g x) (if (eq? x 0) #f (f (- x 1))))
(f y))
At the moment this code doesn't run - g closes over f, but not the other way around.
Is there a canonical way to implement simultaneous binding in Lisp?
In SICP there's a section on internal definitions which covers this subject. In particular, the exercises 4.16, 4.18, 4.19 tell you how to implement different strategies for achieving simultaneous definitions.
The syntax is a bit different, but the idea in the book boils down to transforming this code:
(lambda <vars>
(define u <e1>)
(define v <e2>)
<e3>)
Into this code:
(lambda <vars>
(let ((u '*unassigned*)
(v '*unassigned*))
(set! u <e1>)
(set! v <e2>)
<e3>))
The same idea applies to your with special form. Take a look at the linked book for more implementation details.
In (with (a (+ 2 2))) we are binding a to the value of the expression (+ 2 2), so a becomes 4. But in (with ((f x) (+ x x))) we are doing something else: we are binding f to a function. This is a syntactic sugar for (with (f (lambda (x) (+ x x)))).
To handle this situation, you have to process the bindings in two passes. First collect all the variables and create the environment which contains all of them. Then evaluate the initializing experssions and store their values in the corresponding variables. The evaluation of these expressions takes place in that environment, so every expression has visibility over all the variables. The initialization is done by assignment. The variables can be initially nil or have some trap value which blows up if they are accessed.

how do I use a function as a variable in lisp?

I'm trying to write a function which checks if every element in the list x has property a, so I wrote:
(defun check (a x)
(if (listp x)
(eval (cons 'and (mapcar #'a x)))))
but it doesn't work. (Basically I want a to be the name of a function, say blablabla, and in the body of the check-function, by #'a I want to mean the function blablabla, instead of a function called a.) Now the code above doesn't work. I think in Lisp one should be able to plug in functions. How can I fix it?
(It is literally my first day on lisp, so it might be a stupid question ;)
and BTW I'm using Lispworks 6.0 personal version.)
There is no need to use the sharp-quote syntax here. Its purpose is to use a function name in a variable position, but a is a variable already. Just write a instead of #'a.
You don't need eval you can use apply.
To the problem: You need funcall because you provide a as argument. (Edit: Not in this case.) By quoting you just refer to the function a not the a in this function.
(defun check (a xs)
(if (listp xs)
(every #'identity (mapcar a
xs))))
Better, use loop:
(defun check (a xs)
(if (listp xs)
(loop for x in xs
always (funcall a x))))
Best, use every:
(defun check (a xs)
(if (listp xs)
(every a xs)))
Here is how I would write something like your check function. I tried to give it a more descriptive name.
(defun are-all-elements-fullfilling-fun-p (fun ls)
(every #'identity (mapcar fun ls)))
Edit: Note that a shorter and better definition is
(defun are-all-elements-fullfilling-fun-p (fun ls)
(every fun ls)))
Now let's say we want to call it with this function. Note that I tend to use declarations when possible. I quite often screw something up and debugging is easy if the compiler can figure the error out. Also the code will run faster.
(defun is-even-p (n)
(declare (type number n))
(the boolean (= 0 (mod n 2))))
You have to place the #' here:
(are-all-elements-fullfilling-fun-p #'is-even-p '(1 2 3 4))
(are-all-elements-fullfilling-fun-p #'is-even-p '(38 2 4))