As an attempt to learn more about call/cc in general I saw How does the yin-yang puzzle work? question and this explaination about the yin-yang puzzle:
(let*
(
(yin (
(lambda (cc) (display #\#) cc)
(call/cc (lambda (c) c))
))
(yang (
(lambda (cc) (display #\*) cc)
(call/cc (lambda (c) c))
))
)
(yin yang)
)
I probably (or probably not) understood the yin-yang puzzle concept as of by now. But I found that scheme syntax is not particularly easy to understand, and upon searching I found that ruby have Continuation module. Since ruby syntax follows procedural style, I found that it's much easier to read ruby code than scheme code. Therefore I decided to translate the puzzle to ruby version (I'm both novice at scheme and ruby):
require "continuation"
yin = (lambda do |cc|
print "#"
return cc
end).call(callcc {|c| c})
yang = (lambda do |cc|
print "*"
return cc
end).call(callcc {|c| c})
yin.call(yang)
However this version prints out #*#***********... (demo here) instead of #*#**#***#****#*****#**..., which is not what I expected.
Is my ruby version correct? If it's not correct then I don't really know what's to do from here...
i think your problem that yin and yang will become Continuation and they don't call together but only yang nested inside yin.
yin = (lambda do |cc|
print "#"
return cc # (3) return Continuation (1)
end).call(callcc {|c| c}) # (1) this params call first
# (2) lambda will call immediately -> print the first #
# so yin = Continuation (1)
yang = (lambda do |cc|
print "*"
return cc # (6) return Continuation (4)
end).call(callcc {|c| c}) # (4) this params call first *
# (5) lambda will call immediately -> print the first *
# so yang = Continuation (4)
yin.call(yang)
now we could interpret your code as below
yin = callcc {|c| c} # yin context
print '#'
yang = callcc {|cc| cc} # yang context
print '*'
yin.call(yang)
# end yang context
# end yin context
as you can see, after the first time call (the second # and *) the last line yin.call(yang) will keep call yang yang ( * yang ( * yang ( ..., if you replace by yin.call(yin), the output will be #*#*#*#*...
finally, here is my solution, the idea is that yin and yang will be nested together, the next yang will contains the prev yin + '*' and the next yin will contains the previous yang + '#'
require "continuation"
yin = lambda { |yang|
cc = callcc { |cc| cc }
print "#"
yang.call(cc)
}
yang = lambda { |yin|
cc = callcc { |cc| cc }
print "*"
yin.call(cc)
}
yin.call(yang)
Related
We get:
(defrel (alwayso)
(conde
(#s)
((alwayso))))
(run 1 q
(alwayso)
#u)
The book (2nd ed) says:
"alwayso succeeds, followed by #u, which causes (alwayso) to be retried, which succeeds again".
I still don't get the control flow. Why aren't both arms of the conde tried (continuing in the recursion) before stepping out to #u?
"Why aren't both arms of the conde tried (continuing in the recursion) before stepping out to #u?"
You meant, why the second arm is not tried before stepping out to #u with the result from the first.
The short answer is, lazy-sequences (also, lazy-evaluation) paradigm.
Under the eager evaluation paradigm, each goal produces all if its solutions in full. If their number is unbounded ("infinite"), this means infinite looping, indeed as you expected.
Under the lazy evaluation paradigm, each goal produces its solutions one by one -- meaning, it produces only its first result and stays ready to produce the next when and if requested.
Goals produce their resulting substitutions one by one, as if by yield in Python. So do the combined goals as well. The conde combination combines its subgoal in a certain way (see below), and produces the combined goal's results one by one. Thus
#| (defrel (alwayso)
(conde
(#s)
((alwayso)))) |#
(run 1 q
(alwayso)
#u)
=
(run 1 q
(conde
(#s) ; 1.1
((alwayso))) ; 1.2 -> ; 1
#u) ; 2
run's first goal, the combined goal conde, produces its results one by one, each result being fed to the second run goal, #u, as soon as it is produced.
If all the solutions of run's first subgoal were to be produced before feeding the list of results to the next subgoal, the evaluation would never end for any goal capable of producing infinite list (or more precisely, unbounded stream) of results.
These streams are thus lazy streams, and lists are eager lists. The difference is operational. Under eager scheme, the first subgoal's list is first built in full, and only then processed by the next goal. When the number of results is infinite, building an infinite eager list will take infinite time.
Thus under the eager evaluation paradigm it would indeed get stuck in the recursion inside that conde.
Under the lazy evaluation paradigm, chosen by the book's implementation, it gets stuck in a bigger loop, bouncing off the #u back every time. But the conde works, producing its resulting substitutions successfully one by one.
Scheme itself is an eager language. Delaying the production of the rest of stream is achieved by putting it behind the lambda, Roughly,
(cons 1 rest-of-list)
(an eager list) is replaced with
(cons 1 (^() code-to-produce-the-rest-of-stream))
(a lazy stream).
alwayso is defined so that it produces an infinite stream of copies of its input substitution, unchanged. But it produces them one by one.
Then run feeds this stream from its first goal, to the second goal, #u, which rejects it. Since run 1 demands one solution from its subgoals, it retries them until one solution / substitution goes through.
Which never happens.
So this should result in infinite looping.
Again, both arms are tried -- first, the first one; then, after its (one) result gets rejected by the subsequent #u, the second arm is tried. And the resulting substitution gets rejected, again. Ad infinitum:
;; we have
(defrel (alwayso)
(conde
(#s)
((alwayso))))
;; running:
(run 1 q
(alwayso)
#u)
=
(run 1 q
(conde ; (a OR b) , c
(#s)
((alwayso)))
#u)
=
(run 1 q ; (a , c) OR (b , c)
(conde
(#s #u)
((alwayso) #u)))
=
(run 1 q
(alwayso)
#u)
=
.....
Getting stuck.
Following the implementation's definitions closer,
(defrel (alwayso)
(conde
(#s)
((alwayso))))
= ; by def of defrel; with ^ for lambda
(define (alwayso)
(^s (^() ( (conde
(#s) ; first
((alwayso))) s)))) ; second
= ; by defs of conde, conj and disj
(define (alwayso)
(^s (^() ( (disj2
#s ; first
(alwayso) ) s)))) ; second
= ; by def of disj2
(define (alwayso) ; (-1-)
(^s (^() (append-inf
(#s s) ; first
((alwayso) s)) ))) ; second
= ; by defs of #s and alwayso (-1-)
(define (alwayso)
(^s (^() (append-inf
(list s) ; first
(^() (append-inf ; second
(#s s)
((alwayso) s)) )) )))
= ; by def of append-inf
(define (alwayso)
(^s (^() (cons s ; first
(^() (append-inf ; second
(#s s)
((alwayso) s)) )) )))
= ; by def of append-inf
(define (alwayso)
(^s (^() (cons s
(^() (cons s
((alwayso) s)) )) )))
=
....
so indeed we see here a definition which produces a stream of an unbounded number of copies of the input substitution s, as and when requested, as the result of a call ((alwayso) <s>).
Or, in pseudocode, writing ++ for append-inf and [s] for (list s),
((alwayso) s)
=
((#s OR (alwayso)) s)
=
(#s s) ++ ((alwayso) s)
=
[s] ++ ((#s OR (alwayso)) s)
=
[s] ++ [s] ++ ((#s OR (alwayso)) s)
=
[s] ++ [s] ++ [s] ++ ((#s OR (alwayso)) s)
=
[s s s .... ]
Finally,
(run 1 q (alwayso) #u)
= ; by def of run
(let ((q (var 'q)))
(map (reify q)
(run-goal 1 (conj (alwayso) #u))))
= ; by defs of run-goal and conj
(let ((q (var 'q)))
(map (reify q)
(take-inf 1 ((conj2 (alwayso) #u) empty-s))))
= ; by defs of conj2 and #u
(let ((q (var 'q)))
(map (reify q)
(take-inf 1
(append-map-inf (^s '())
((alwayso) empty-s)))))
and no matter how many empty-s's it applies the (^s '()) to, to append the results together, all the results are empty lists, so it can't take even one of the contained results because there are none. In pseudocode, writing s0 for empty-s,
(take-inf 1
(append-map-inf (^s '())
((alwayso) empty-s)))
= ; as established above
(take-inf 1 (append-map-inf (^s [])
[ s0 s0 s0 .... ]))
= ; by def of append-map-inf
(take-inf 1
(append-inf ((^s []) s0)
(append-map-inf (^s [])
[ s0 s0 .... ])))
= ; by beta-reduction
(take-inf 1
(append-inf []
(append-map-inf (^s [])
[ s0 s0 .... ])))
= ; be def of append-if
(take-inf 1
(append-map-inf (^s [])
[ s0 s0 .... ]))
= ; and we're back where we've started
<LOOPING>
Or, symbolically,
(take 1 (append-map-inf (^s [])
[ s0 s0 s0 .... ]))
=
(take 1 (append-inf [ [] [] [] .... ]))
=
(take 1 [ ; sic!
So it gets stuck.
Can the common-lisp pretty printer be easily configured to print out any deeply nested list in "outline" form, or is this a job for format? Eg, '(a (b c (d e (f)) g)) should come out looking something like the following, where each cdr element steps down a level from the car:
A
B
C
D
E
F
G
Look at the ~nT format directive. This will print the next argument at the n-th column:
(format t "~30T~a" 'a)
A
If the column is variable, then use ~vt to use the first argument as the column value:
(format t "~VT~a" 10 'a)
A
This will print 'A' at the 10-th column
I'm trying to create a function that will take a string and display it.
(defun closing (s)
(format t "~{~a~}" ("Sincerely," "\n" s)))
What I hope to get is
Sincerely,
Frank
if "Frank" is the string I passed in. It complains of the variable S is defined but never used. What am I doing wrong?
Trying to use format alone: If I declare urname as a defparameter to be "Frank", the following doesn't print Frank, rather just the variable name. (Without quote it complains of urname not being a function.)
(format t "~{~a~}" '(urname urname urname))
How can I feed variables to format?
There are three issues here: (1) The code you posted doesn't just have the problem of not using s; it's also trying to call the string "Sincerely" as a function; (2) quoting a list means you'll get exactly what's quoted (e.g., a list of symbols, not a list of values of variables); (3) calling format with lists.
(something other-stuff...) is a function call
When I put the code you posted into SBCL, I get some very specific and helpful output:
CL-USER> (defun closing (s)
(format t "~{~a~}" ("Sincerely," "\n" s)))
; in: DEFUN CLOSING
; ("Sincerely," "n" S)
;
; caught ERROR:
; illegal function call
; (SB-INT:NAMED-LAMBDA CLOSING
; (S)
; (BLOCK CLOSING (FORMAT T "~{~a~}" ("Sincerely," "n" S))))
;
; caught STYLE-WARNING:
; The variable S is defined but never used.
;
; compilation unit finished
; caught 1 ERROR condition
; caught 1 STYLE-WARNING condition
("Sincerely," "\n" s) is an illegal function call, since a string, like "Sincerely", can't have a function binding. Since SBCL sees the problem in that, it recognizes that the one thing that s might have been used for (i.e., an argument to a function call), can't happen. That's why you'll get the error, and then the associated style warning.
Creating lists of values
The second is probably answered in other questions already, but the short answer is that you want (list x y z), not '(x y z). The former calls the function list with the values of the variables x, y, and z, while the latter denotes a literal list of the symbols x, y, and z.
CL-USER> (let ((a 42)
(b 89))
(print '(a b)) ; a list of two symbols
(print (list a b))) ; a list of two numbers
(A B)
(42 89)
Format, iteration, &c.
The third is probably more interesting, since format has so many possibilities. The ~{ and ~} in your example are used for iterating over values in a list. First, let's look at a simple example: you can just use the format directive ~a and call format with the arguments you want to splice in:
CL-USER> (let ((closing "Sincerely")
(name "Frank"))
(format t "~a,~%~a" closing name))
Sincerely,
Frank
Now, if you need to print multiple values, you can use ~{ and ~} to have format iterate over a list of values:
CL-USER> (let ((closing "Sincerely")
(names '("Frank" "John")))
(format t "~a,~{~%~a~}" closing names))
Sincerely,
Frank
John
If the names are the values of variables, then you can either create a list containing those values:
CL-USER> (let ((closing "Sincerely")
(name1 "Frank")
(name2 "John"))
(format t "~a,~{~%~a~}" closing (list name1 name2)))
Sincerely,
Frank
John
or you can change ~{ to ~#{ and have format read the remaining arguments as the list:
CL-USER> (let ((closing "Sincerely")
(name1 "Frank")
(name2 "John"))
(format t "~a,~#{~%~a~}" closing name1 name2))
Sincerely,
Frank
John
You should read a tutorial about format, from here for example
For an easy explanation
(format
(destination-stream usually t for standard output nil to form a string)
(here comes the string)
(&rest variables that should write in the string where is an ~A and by position like String.format in java or c))
in your case, you need the symbol ~% or use the character for return in common lisp
CL-USER> (defun closing (s) (format t "~A~%~%~A" "Sincerely," s))
CLOSING
CL-USER> (closing "paco")
Sincerely,
paco
NIL
The nil say that the functions returns null, and the other is the standard output if you want to return a string, put nil instead of t
Let's say I have a program like this:
(define (foo x)
(local
((define y (- x 1)))
(* x y)))
(foo 3)
I want to be able to open a REPL between lines 3 and 4, such that I can explore (and possibly modify) the values of x and y by executing arbitrary statements.
To do this in Ruby, I would take the equivalent program:
def foo(x)
lambda {
y = x - 1
x * y
}.call
end
puts (foo 3)
And modify it by adding a call to pry to give me a nicely-scoped repl where I want it:
require 'pry'
def foo(x)
lambda {
y = x - 1
binding.pry
x * y
}.call
end
puts (foo 3)
To do it in js, I would run this program under Firebug and just put a breakpoint on line 4:
foo = function(x) {
return (function(){
var y = x - 1;
return x * y;
})();
};
console.log(foo(3));
And then I could explore stuff in the evaluation window.
Is there anything I can do to get this in Racket? The closest I've found is DrScheme's debugger, but that just presents all the values of the current scope, it doesn't let you explore them in a REPL as far as I can see.
This isn't answering your original question, it's in response to your comment about making your own. I thought that was a really interesting idea so I explored it. What I was able to figure out:
Let's say you want this to work:
(define top-x 10)
(define (f)
(for ([i 10])
(displayln i)
(when (= i 5)
(pry)))) ; <= drop into a REPL here, resume after exiting REPL
A first attempt at pry:
(define (pry)
(let loop ()
(display "PRY> ")
(define x (read))
(unless (or (eof-object? x) (equal? x '(unquote exit)))
(pretty-print (eval x))
(loop))))
This seems to work:
> (f)
0
1
2
PRY> (+ 10 10)
20
PRY> ,exit
3
4
>
But although it lets you access Racket functions like +, you can't access even your top-level variables like top-x:
> (f)
0
1
2
PRY> top-x
; top-x: undefined;
; cannot reference undefined identifier
You can get the top-level stuff by giving eval access to the current namespace, as explained here. So pry needs a namespace argument:
(define (pry ns)
(let loop ()
(display "PRY> ")
(define x (read))
(unless (or (eof-object? x) (equal? x '(unquote exit)))
(pretty-print (eval x ns)) ; <---
(loop))))
And to get that argument you need this incantation to your debugee file:
(define-namespace-anchor a) ; <---
(define ns (namespace-anchor->namespace a)) ; <---
(define top-x 10)
(define (f)
(for ([i 5])
(displayln i)
(when (= i 2)
(pry ns)))) ; <---
Now the REPL can see and change top-x:
> (f)
0
1
2
PRY> top-x
10
PRY> (set! top-x 20)
#<void>
PRY> top-x
20
PRY> ,exit
3
4
>
Cool! But it can't change the local variable, i:
> (f)
0
1
2
PRY> i
; i: undefined;
; cannot reference an identifier before its definition
Shoot. The reason why is explained here.
You might imagine that even though eval cannot see the local bindings in broken-eval-formula, there must actually be a data structure mapping x to 2 and y to 3, and you would like a way to get that data structure. In fact, no such data structure exists; the compiler is free to replace every use of x with 2 at compile time, so that the local binding of x does not exist in any concrete sense at run-time. Even when variables cannot be eliminated by constant-folding, normally the names of the variables can be eliminated, and the data structures that hold local values do not resemble a mapping from names to values.
You might say, OK, but in that case...
How does DrRacket provide a debugger?
From what I was able to figure out, DrRacket does this by annotating the syntax before evaluating the program. From drracket/gui-debugger/annotator.rkt:
;; annotate-stx inserts annotations around each expression that introduces a
;; new scope: let, lambda, and function calls. These annotations reify the
;; call stack, and allows to list the current variable in scope, look up
;; their value, as well as change their value. The reified stack is accessed
;; via the CURRENT-CONTINUATION-MARKS using the key DEBUG-KEY
So I think that would be the jumping-off point if you wanted to tackle this.
In the DrRacked IDE you have a DEBUG Q >| button. You can step through your program or you can do as you said in other languages, press right mouse button at the expression you want to investigate and either choose continue to this point for once only or pause at this point for a breakpoint, then press GO > to run the program.
To inspect or change x, put you mouse pointer over it and use right mouse button. To change you choose (set! x ...) in the menu.
As for the in language repl, You could make your own (pry) to start a repl in there and in Common Lisp you could have just signaled an error to get to the nice debugger.
I'm trying to translate the following scheme code into Mathematica (version 8, if that matters):
(define (((lift g) . fs) . args)
(apply g
(map (lambda (f) (apply f args))
fs)))
Then, you can do things like:
(let ((add (lift +))
(square (lift sqr)))
((add (square sin) (square cos)) 42))
; returns 1, since sin^2(42) + cos^2(42) = 1
The part (add (square sin) (square cos)) creates a function x -> sin^2(x) + cos^2(x).
Anyway, I tried coding this in Mathematica, but I can't seem to get very far. Here's what I want to write:
lift[g_] := Function[{fs__}, Function[{args__},
g ## Map[(# ## args)&, fs]]]
I want fs__ and args__ to be bound to the list of all arguments to their respective functions. But then Mathematica complains that the "parameter specification" for Function should be "a symbol or a list of symbols". I know that I can use the ()& style anonymous functions and use ## to get all arguments, but the problem is that when I nest two of these anonymous functions, I lose the ability to access the outer arguments from within the inner function.
How can I write anonymous functions with variable arity (and named arguments)? Or should I solve this problem another way in Mathematica?
I'm not sure if this function does what you want, but you can capture the SlotSequence (##) of the outer function using With
lift[g_] := Function[
With[{fs = ##},
Function[
With[{args = ##},
g ## Map[(#[args]) &, List[fs]]]]]]
Then:
lift[f][a, b][c, d]
-> f[a[c, d], b[c, d]]
Or, more readable:
lift[g_] := Function[
With[{fs = g[##]},
Through[fs[##]] &]]
nikie gave a great answer. I hope this one complements it.
You can create temporary functions using Module, which gives you the full set of pattern options for the parameter specification. For example, using nikie's concise method:
lift1[g_] := Module[{fn}, fn[a__] := Through[g[a][##]] &; fn]
lift1[f][a, b][c, d]
f[a[c, d], b[c, d]]
In this particular case you could also use a SubValues rule like this:
lift2[g_][h__] := Through[g[h][##]] &
lift2[f][a, b][c, d]
f[a[c, d], b[c, d]]
Or even without Function at all:
lift3[g_][h__][i__] := Through[ g[h][i] ]
lift3[f][a, b][c, d]
f[a[c, d], b[c, d]]