beta reduction: correct way to replace bound variables? - lambda-calculus

say I have the following example of a lambda expression with \x meant to represent lambda x
What would the beta reduction of the following be?
(\x.\x.(x x)) \z.z
My first instinct would have been for this to be
\x.(\z.z \z.z)
But someone I spoke with was of the opinion that the second \x would also be replaced with \z.z
which would mean it is really
\(\z.z).(\z.z \z.z)
Can someone please clarify what the correct approach would be. I can't say I really understand the second approach.

Actually, (\x.\x.(x x)) \z.z is alpha equivalent to (\x.\y.(y y)) \z.z because variables are always bound to the closest lambda abstraction.
This means (\x.\x.(x x)) \z.z is beta equivalent to \x.(x x).
Substitution is never done on lambda abstractions, the \x. part.

Related

Scheme : How to quote result of function call?

Is it possible to quote result of function call?
For example
(quoteresult (+ 1 1)) => '2
At first blush, your question doesn’t really make any sense. “Quoting” is a thing that can be performed on datums in a piece of source code. “Quoting” a runtime value is at best a no-op and at worst nonsensical.
The example in your question illustrates why it doesn’t make any sense. Your so-called quoteresult form would evaluate (+ 1 1) to produce '2, but '2 evaluates to 2, the same thing (+ 1 1) evaluates to. How would the result of quoteresult ever be different from ordinary evaluation?
If, however, you want to actually produce a quote expression to be handed off to some use of dynamic evaluation (with the usual disclaimer that that is probably a bad idea), then you need only generate a list of two elements: the symbol quote and your function’s result. If that’s the case, you can implement quoteresult quite simply:
(define (quoteresult x)
(list 'quote x))
This is, however, of limited usefulness for most programs.
For more information on what quoting is and how it works, see What is the difference between quote and list?.

(Clojure) Make a partial function instead of throwing an arity exception with too few arguments?

If you give a function too few arguments, it complains:
user=> (map-indexed vector)
ArityException Wrong number of args (1) passed to: core$map-indexed
clojure.lang.AFn.throwArity (AFn.java:437)
Suppose I want this do something handy instead, like automagically calling (partial map-indexed vector), and I want this new rule to work with every function without having to rewrite all of them. Is there a way to accomplish that, or is there some good reason it's not possible/not idiomatic?
You have answered your own question, partial is the way to go. You should explain your use case more so that a better answer can be given.
Besides, map-indexed expects a function of arity 2 as the first argument and a collection as the second.
The following returns a function that does what you want (I guess).
(defn foo [f] (fn [] (map-indexed f vector)))
EDIT
I misunderstood the use of vector as was pointed out by amalloy. It's not vector as data but as function.
Apart from the use of fn as shown above and partial as mentioned earlier, perhaps you could create a single-character-name synonym (or a really simple macro) which would expand to a call to partial. If you chose $, it would be ($ map-indexed vector).
You could do something like this for any function you define
(defn f
;; The "real" f
([x y z] (whatever-f-does x y z))
;; Overloads to "automagically" construct partial applications
([x] (partial f x))
([x y] (partial f x y)))
Of course, this can be abstracted with a macro, but that is the pattern.
I don't know whether this is a good idea. It's probably not what most Lispers would expect from most functions, but I recon it could be quite useful in some contexts.
There are also some limitations to this approach. Here are a few I thought of:
It's only useful for functions you write, or happen to be written by others who also use that pattern.
It introduces ambiguity when multiple arity is involved (i.e., if f is a function of either 2 or 3 arguments, is (f x y) a complete application of f or a partial application?)
It can't really handle variable arity either (you run into the same problems with ambiguity).
Perhaps a better approach would be to introduce a different function to do the partial application. For example:
(defn partial-f [& args] (apply partial f args))
Of course, you would want to choose a better name than "partial-f". For instance for map, you might use mapper. And for map-indexed, perhaps indexed-mapper would make sense.
Transducers (will) do exactly this for sequence functions, among other cool things.
See: http://blog.cognitect.com/blog/2014/8/6/transducers-are-coming

I can't seem to wrap my mind around call/cc in Scheme

Does anyone have a good guide as to how it works? Something with visual aids would be nice, every guide I've come across all seem to say the same thing I need a fresh take on it.
Here's the diagram that was left on our CS lab's whiteboard. So you're going to fetch some apples, and you grab a continuation before you begin. You wander through the forest, collecting apples, when at the end you apply your continuation on your apples. Suddenly, you find yourself where you were before you went into the forest, except with all of your apples.
(display
(call/cc (lambda (k)
(begin
(call-with-forest
(lambda (f)
(k (collect-apples f))))
(get-eaten-by-a-bear)))))
=> some apples (and you're not eaten by a bear)
I think a Bar Mitzvah and buried gold might have been involved.
Have a look at the continuation part of PLAI -- it's very "practical
oriented", and it uses a "black-hole" visualization for continuations that can help you
understand it.
There is no shortcut in learning call/cc. Read the chapters in The Scheme Programming Language or Teach Yourself Scheme in Fixnum Days.
I found that it helps to visualize the call stack. When evaluating an expression, keep track of the call stack at every step. (See for example http://4.flowsnake.org/archives/602) This may be non-intuitive at first, because in most languages the call stack is implicit; you don't get to manipulate it directly.
Now think of a continuation as a function that saves the call stack. When that function is called (with a value X), it restores the saved call stack, then passes X to it.
Never likes visual representation of call/cc as I can't reflect it back to the code (yes, poor imagination) ;)
Anyway, I think it is easier start not with call/cc but with call/ec (escape continuation) if you already familiar with exceptions in other languages.
Here is some code which should evaluate to value:
(lambda (x) (/ 1 x))
What if x will be equal '0'? In other languages we can throw exception, what about scheme?
We can throw it too!
(lambda (x) (call/ec (cont)
(if (= x 0) (cont "Oh noes!") (/ 1 x))))
call/ec (as well as call/cc) is works like "try" here. In imperative languages you can easily jump out of function simply returning value or throwing exception.
In functional you can't jump out, you should evaluate something. And call/* comes to rescue.
What it does it represent expression under "call/ec" as function (this named "cont" in my case) with one argument. When this function is called it replaces the WHOLE call/* to it's argument.
So, when (cont "Oh noes!") replaces (call/ec (cont) (if (= x 0) (cont "Oh noes!") (/ 1 x))) to "Oh noes!" string.
call/cc and call/ec are almost equals to each other except ec simplier to implement. It allows only jump up, whil cc may be jumped down from outside.

Scheme Infix to Postfix

Let me establish that this is part of a class assignment, so I'm definitely not looking for a complete code answer. Essentially we need to write a converter in Scheme that takes a list representing a mathematical equation in infix format and then output a list with the equation in postfix format.
We've been provided with the algorithm to do so, simple enough. The issue is that there is a restriction against using any of the available imperative language features. I can't figure out how to do this in a purely functional manner. This is our fist introduction to functional programming in my program.
I know I'm going to be using recursion to iterate over the list of items in the infix expression like such.
(define (itp ifExpr)
(
; do some processing using cond statement
(itp (cdr ifExpr))
))
I have all of the processing implemented (at least as best I can without knowing how to do the rest) but the algorithm I'm using to implement this requires that operators be pushed onto a stack and used later. My question is how do I implement a stack in this function that is available to all of the recursive calls as well?
(Updated in response to the OP's comment; see the new section below the original answer.)
Use a list for the stack and make it one of the loop variables. E.g.
(let loop ((stack (list))
... ; other loop variables here,
; like e.g. what remains of the infix expression
)
... ; loop body
)
Then whenever you want to change what's on the stack at the next iteration, well, basically just do so.
(loop (cons 'foo stack) ...)
Also note that if you need to make a bunch of "updates" in sequence, you can often model that with a let* form. This doesn't really work with vectors in Scheme (though it does work with Clojure's persistent vectors, if you care to look into them), but it does with scalar values and lists, as well as SRFI 40/41 streams.
In response to your comment about loops being ruled out as an "imperative" feature:
(let loop ((foo foo-val)
(bar bar-val))
(do-stuff))
is syntactic sugar for
(letrec ((loop (lambda (foo bar) (do-stuff))))
(loop foo-val bar-val))
letrec then expands to a form of let which is likely to use something equivalent to a set! or local define internally, but is considered perfectly functional. You are free to use some other symbol in place of loop, by the way. Also, this kind of let is called 'named let' (or sometimes 'tagged').
You will likely remember that the basic form of let:
(let ((foo foo-val)
(bar bar-val))
(do-stuff))
is also syntactic sugar over a clever use of lambda:
((lambda (foo bar) (do-stuff)) foo-val bar-val)
so it all boils down to procedure application, as is usual in Scheme.
Named let makes self-recursion prettier, that's all; and as I'm sure you already know, (self-) recursion with tail calls is the way to go when modelling iterative computational processes in a functional way.
Clearly this particular "loopy" construct lends itself pretty well to imperative programming too -- just use set! or data structure mutators in the loop's body if that's what you want to do -- but if you stay away from destructive function calls, there's nothing inherently imperative about looping through recursion or the tagged let itself at all. In fact, looping through recursion is one of the most basic techniques in functional programming and the whole point of this kind of homework would have to be teaching precisely that... :-)
If you really feel uncertain about whether it's ok to use it (or whether it will be clear enough that you understand the pattern involved if you just use a named let), then you could just desugar it as explained above (possibly using a local define rather than letrec).
I'm not sure I understand this all correctly, but what's wrong with this simpler solution:
First:
You test if your argument is indeed a list:
If yes: Append the the MAP of the function over the tail (map postfixer (cdr lst)) to the a list containing only the head. The Map just applies the postfixer again to each sequential element of the tail.
If not, just return the argument unchanged.
Three lines of Scheme in my implementation, translates:
(postfixer '(= 7 (/ (+ 10 4) 2)))
To:
(7 ((10 4 +) 2 /) =)
The recursion via map needs no looping, not even tail looping, no mutation and shows the functional style by applying map. Unless I'm totally misunderstanding your point here, I don't see the need for all that complexity above.
Edit: Oh, now I read, infix, not prefix, to postfix. Well, the same general idea applies except taking the second element and not the first.

Finding if a number is the power of 2 in Scheme

I'm fairly new to Scheme and am attempting to learn it on my own from scratch. I'm stuck on the syntax of this problem. I know that if I want to find out if a number is a power of 2, in C for instance, I would simply do:
return (x & (x - 1)) == 0;
which would return true or false. How would I be able to convert this into a couple simple lines in Scheme?
I'll give you a hint since you're trying to learn the language.
Scheme has a function called (bitwise-and ...) which is equivalent to the & operator in C (there is also (bitwise-xor ...), (bitwise-not ..), etc., which do the expected thing).
(Here is the documentation of the (bitwise-and ...) function)
Given that, would you be able to translate what you've written in your question into Scheme code?
N.B: For a problem like this, you really don't need to resort to bitwise operations when using Scheme. Realistically, you should be writing a (possibly probably tail) recursive function that will compute this for you.
You can do this using a built in bitwise operator.
(define (pow2? x)
(= (bitwise-and x (- x 1))
0))
Scheme also has biwise operators.
But if you really want to develop your scheme skills, you should write a function that decides if an integer is a power of 2 by recursively dividing it by 2 until you are left with either 2 or with an odd number. This would be very inefficient, but really cool nonetheless.

Resources