Re: [racket-users] parameterized logging

2018-08-07 Thread Sean Kanaley
Thanks, Neil. Unfortunately #2 didn't work. The historically written
define-logger calls like log-something-debug overwrites the "foo" topic
with "something". If only they were appended together. #3 can't intercept
logs of define-logger loggers (if a woodchuck could...) even with
topic/level hardcoded because the #:logger keyword is also needed. So it
seems like the usage would be a series of nested with-intercepted-loggings,
one for each define-logger. Lastly, #1 is what I'm trying to avoid :)

To be fair, either #1 or #3 is fully *practical*, but the Racketeer in me
would prefer to fully automate this. The "proper" solution seems to require
a Racket change.

Is #3 a bug? Or I might be getting confused at the timing with the
define-logger = current-logger being used to write the log and the
interceptor reverting to the previous logger, but the code that seems like
it should work here:

#lang racket/base
(require racket/logging)

(define-logger x)

;works, no define-logger topic though
(let ([thread-id "hurray"])
  (with-intercepted-logging
  (λ (v)
(printf "~a: ~a~n" thread-id (vector-ref v 1)))
(λ ()
  (log-debug "we interrupt this program to bring you this important
message"))
'debug))

;doesn't work
(let ([thread-id "hurray"])
  (with-intercepted-logging
  (λ (v)
(printf "~a: ~a~n" thread-id (vector-ref v 1)))
(λ ()
  (log-x-debug "we interrupt this program to bring you this important
message"))
'debug))

;works but messy for many define-loggers
(let ([thread-id "hurray"])
  (with-intercepted-logging
  #:logger x-logger
  (λ (v)
(printf "~a: ~a~n" thread-id (vector-ref v 1)))
(λ ()
  (log-x-debug "we interrupt this program to bring you this important
message"))
'debug))

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[racket-users] parameterized logging

2018-08-06 Thread Sean Kanaley
Hi all,

Is there a way to automatically send say a prefix string with many already
coded logger invocations?

For example, to go from:


(thread
...
(log-debug "information specific to particular thread, without mention of
which thread"))


to:


(thread
...
(parameterize ([current-logger-prefix "thread identifier"])
...
(log-debug "information specific to particular thread, without mention of
which thread")))


where the latter log-debug is defined to do (format "~a: ~a"
(current-logger-prefix) message).

Since the receiver is in a different thread, directly coding a receiver to
use the parameter won't work. And since it's asynchronous, relying on
globals won't work.

The use case if somebody has a different idea altogether is a webserver
supporting multitenancy. The request handler for tenant "X" should log as
"X: ".

It looks like this would be easy to add to racket/private/logger if there's
no way short of mass refactoring, so it's not hopeless.

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [racket-users] On Richard P. Gabriel’s “The Structure of a Programming Language Revolution”

2018-04-30 Thread Sean Kanaley
> and using version control as the primary source of truth. Reproducibility
is important.

> we got ourselves confused on occasion and the more it happened, the more
it became clear to me that we needed to shift to a more static view

I want to voice what I think is agreement that reliability of the rest of
the universe is important (all that is not "the code right in front of
me"). Correct output is a function of correct input and the correct
function that processes it. So users are intentionally guarded against and
programmers are responsible for config files and source. Everything else
*has* to work. It's extremely confusing (time-wasting) to debug your code
only to later learn the server has the old version of code on it, for
example, or that, god forbid, gcc compiles 2+3 to 2+4 on 13 Aug every year.
The config file is bad enough, but I don't know a solution to that, and
it's under my control in my dev environment. It can definitely get
confusing when the production environment malfunctions due to a config
issue. But, the more confidence the programmer has in their code and the
universe as a whole, the more easily they can just declare "it's probably
the config".

Programming Systems introduce additional mutations of the universe beyond
the source code that effectively undermine the source code. The
"referential transparency" between programmer thought and users' code
execution is lost, unless the programmer manages to perfectly mutate their
thoughts in parallel with the changes to the runtime environment. But we
make mistakes with plain old code, so I'm gonna say, "not happening".

On the other hand, mutation is for efficiency. If there's a case where
refreshing all deployments after a source change takes far too long, a
compromise may be needed. But I don't work in a sufficiently complex
product that would benefit from ditching reliability in favor of
tinkerability, and if it was that complex, I'd probably prefer reliability!

So, I recommend sticking with "Racket AST implies the set of program
outputs".

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [racket-users] Unit test inner procedures

2017-12-06 Thread Sean Kanaley
Regarding submod testing, would it make sense to have a submod* form that
recursively imports? I've recently become a fan of this approach to testing
inner procedures but it seems to require both (submod "." ) (submod
"."  test), or maybe a version that specifically imports all tests
recursively.

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [racket-users] Can a macro have an affect above/outside its scope?

2016-03-21 Thread Sean Kanaley
What if you define define as define/provide and define definep as define?

That doesn't answer the question about black magic though.

On Mon, Mar 21, 2016 at 10:51 AM, Brian Adkins 
wrote:

> I've been porting my friend's Elixir code to Racket with great success.
> When I asked what the equivalent of (provide my-func) was in Elixir, they
> mentioned that you can define a private function with defp instead of def.
> For example:
>
> defmodule MyModule do
>   def foo(a) do
> ...
>   end
>
>   defp bar(b) do
> ...
>   end
> end
>
> vs.
>
> #lang racket
> (provide foo)
>
> (define (foo a) ... )
> (define (bar a) ... )
>
>
> I prefer the Racket way, but it made me curious about the possibility of a
> definep macro that would work similarly as a thought experiment.
>
> Is it possible to do the following?
>
> #lang racket
>
> (define (foo a) ... )
> (definep (bar a) ... )
>
> I'm not asking for someone to help with definep - I'm just curious about
> the possibility of a macro adding/modifying something outside of its scope.
> In other words, could a definep macro create or modify the proper (provide)
> construct to export foo and not bar ?
>
> Thanks,
> Brian
>
> --
> You received this message because you are subscribed to the Google Groups
> "Racket Users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to racket-users+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [racket-users] racket users fight for their right to colon keywords

2015-10-16 Thread Sean Kanaley
While were at it, can we make :long-keyword [3] => :long-keyword
[long-keyword 3] ?

And can we make define => =, and = => == ?

In general, can we "Huffman encode" forms by average form usage frequency?

(But seriously, the first one would be nice)

On Fri, Oct 16, 2015 at 6:05 PM, Gustavo Massaccesi 
wrote:

> I agree. I think that :xyz doesn't look special enough, and with #:xyz
> is clear that the reader is doing something special.
>
> Gustavo
>
> On Thu, Oct 15, 2015 at 1:00 PM, Laurent  wrote:
> > On Thu, Oct 15, 2015 at 3:25 PM, Deren Dohoda 
> > wrote:
> >>
> >> I don't have a very strong opinion, it seems like convenient syntax, but
> >> half of what draws me to stick with lisps is the low amount of syntax.
> >> Pound-colon has a strong line noise quality to it which colons lack,  I
> >> admit. But they also have an explicit feel which colons lack.
> >
> > In particular, they have a "reader syntax" feeling, as most things that
> > start with a pound in Racket. I initially didn't like them for keywords,
> but
> > now I'm feeling somewhat ok with them. Having two characters to prefix a
> > keyword argument is a lot though, especially when one uses them so much.
> >
> > Laurent
> >
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Racket Users" group.
> > To unsubscribe from this group and stop receiving emails from it, send an
> > email to racket-users+unsubscr...@googlegroups.com.
> > For more options, visit https://groups.google.com/d/optout.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Racket Users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to racket-users+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [racket-users] Finding an old patch

2015-10-06 Thread Sean Kanaley
Hi Sam and Vincent,

Yes the old URL now works, thanks! I used the word patch because the old
url was .../plt/patch/... .

Reply2all ftw

On Tue, Oct 6, 2015 at 6:54 PM, Vincent St-Amour <
stamo...@eecs.northwestern.edu> wrote:

> What was the URL for the old patch?
>
> If the URL includes the commit hash, finding its new location should be
> easy.
>
> Vincent
>
>
>
> On Tue, 06 Oct 2015 15:26:22 -0500,
> Sean Kanaley wrote:
> >
> > Hi all,
> >
> > Now that the repository has moved from git.racket-lang..., I can no
> > longer find a particular patch. I also have no idea what it did, only
> > that it was necessary. Is there a way to find it based on the old url?
> >
> > Failing that, I would try installing the base version along side and
> > diffing the whole source. Hopefully the patch was minor.
> >
> > Thanks
> >
> > --
> > You received this message because you are subscribed to the Google
> > Groups "Racket Users" group.
> > To unsubscribe from this group and stop receiving emails from it, send
> > an email to racket-users+unsubscr...@googlegroups.com.
> > For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[racket-users] Finding an old patch

2015-10-06 Thread Sean Kanaley
Hi all,

Now that the repository has moved from git.racket-lang..., I can no longer
find a particular patch. I also have no idea what it did, only that it was
necessary. Is there a way to find it based on the old url?

Failing that, I would try installing the base version along side and
diffing the whole source. Hopefully the patch was minor.

Thanks

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [racket-users] eval PSA (was Sending Closures to Places)

2015-08-04 Thread Sean Kanaley
" I cannot think of any good uses for eval in Racket."

Any time the mental time spent using eval (or defmacro) is less than that
of figuring out how to not use eval or defmacro by using
let-parameterize-syntax-splicing-local-transformer-binding-apply-values
instead, which for the average programmer is probably always. Programming
in perfect Racket (or any language) is like finding the optimal solution to
the traveling salesman, or finding a large prime with 100% certainty. You
are spending disproportionate efforts for the ~same result. If I have a
square peg that has to go into a round hole, I can just apply a lot of
force rather than going to the store and buying a new peg. How bad this
result is depends on how gigantic the wall is that suffered the damage. A
big enough program will be sufficiently buggy that a clear use of eval is
probably no big deal, e.g.


(define (launch-nukes target)
  (for ([i 10])
 (launch 'nuke 'civilian)))

(define (confirmation target)
  (eval '(printf "Are you sure you wish to nuke ~a?" target) namespace)
  ...)

To a purist, the above code is horrifying.


On Tue, Aug 4, 2015 at 10:34 AM, Alexis King  wrote:

> > I don't know why but at some point in the 20th century people really
> became afraid of viewing programs as pure data (which they are) and started
> to call it metacircular (which of course also refers to other properties of
> a list processor treating each and every start of list, i.e. opening
> parenthese, as an apply instruction).
>
> *sigh* Okay, I’ll bite.
>
> I think I can understand the appeal of wanting to love eval. It’s a Lisp
> tradition to have it, and indeed, it is still one of the first things that
> people mention when describing how Lisps are different from other
> languages. Turning around and admitting that one of our signature features
> should be avoided is not only confusing, it seems to reduce Lisp back to
> the level of any other language. If eval is out, what makes Lisps special
> anymore?
>
> So of course it can seem freeing to come to the conclusion that all those
> people warning about eval are just “afraid of its power”, and we have so
> much to gain by “rediscovering” this tool, but that’s not really true. Eval
> may not be evil, but I’d consider it one of the worst possible code smells.
> I cannot think of any good uses for eval in Racket.
>
> > One the one hand I reject any security concerns about eval which is as
> good or bad as input data as are the key codes from your favorite event
> handling loop determining your programs actions. A simple (send object
> message arguments) could be implemented by evaluating message in the
> environment of object, i.e. applying it to the arguments. The use of eval
> shouldn't be restricted to proclaimed  designers of algorithmic notations
> but using it correctly needs some understanding of Scheme and its
> specifications. That necessary knowledge used to be conveyed in a lecture
> of one semester at the MIT with SICP (I've read).
>
> The argument that all (interesting) programs are input-driven, but to then
> draw the conclusion that eval is no more dangerous than other methods of
> input processing would be quite the fallacy. But I agree with some other
> people in this thread that it isn’t really explained why eval is bad, and
> really, I’ve never read an explanation that has wholly satisfied me.
>
> I don’t think the real reason for spurning eval is to avoid security
> problems or to handle code evaluation in different contexts (though both of
> those things are highly related to the “core” problem with eval). I’d argue
> that the problem with eval is one of abstraction: eval is barely any better
> than writing directly to the underlying runtime or virtual machine.
>
> Scheme is largely derived from one of the most powerful abstractions in
> the history of computer science, the closure. It goes by plenty of names,
> but the reason I pick “closure” is that it indicates precisely why the
> construct is far superior to eval: it keeps its context with it. When you
> pass closures around in code, they maintain the collection of values from
> their original scope, and when you call a closure, you can’t get at the
> values in the calling scope. Closures are more or less reified eval.
>
> As programmers, it is incredibly important to have the guarantees that
> closures provide because that allows us to abstract upon them. We can go
> higher-order, and in doing so, it is possible to create entire DSLs without
> even so much as a macro system. Doing that with eval is almost impossible
> because eval is not *composable*. The solution is not “an eval that carries
> around its lexical context” because then you have pretty much reinvented
> closures.
>
> So what was the original title of this thread again? Oh right, “Sending
> Closures to Places”. Obviously in that case, our nice little closure
> abstraction has failed us. Why? Because that context can’t be serialized in
> the general case. Dropping dow

Re: [racket-users] http-sendrecv with Google geocode

2015-04-21 Thread Sean Kanaley
Hi George,

I'm not sure then -- I am in Racket 6.1.1. Here is the source that worked
for me:

#lang racket
(require net/http-client
 net/uri-codec)

(define (lookup address)
  (let [
(form-data  (alist->form-urlencoded
 (list (cons 'address address)
   )))

(response #f)
(lat  #f)
(long #f)
   ]

(printf "Looking up ~s~n" address)
(printf "=> ~s~n" form-data)

(with-handlers [
(exn:fail?
 (lambda (e)
  3; (fprintf (ferr) "~n~n%%~n~a~n%%~n" (format "Error:
~a" (exn-message e)))
   ))
   ]
  (let-values [
   ((errcode header port)
(http-sendrecv "maps.googleapis.com"
   (string-append "
http://maps.googleapis.com/maps/api/geocode/json?"; form-data)
   ;#:ssl? ssl?
   ;#:port port
   #:version #"1.1"
   #:method  #"GET"
   #:headers (list "Content-Type:
application/x-www-form-urlencoded")
   ;#:data form-data
   ;#:content-decode decodes
   ))
  ]
(set! response (port->string port))
;(set! response (read-json port))
(printf "=> ~s~n" response)
))

;(fprintf (ferr) "lat:~s long:~s~n"  lat long )
(values lat long)
))



(I commented out the fprintfs to avoid dealing with ferr.)

It won't work if #:data is uncommented. I hope that helps, otherwise I'm
stuck too.

On Tue, Apr 21, 2015 at 2:23 AM, George Neuner  wrote:

>  Hi Sean,
>
> On 4/21/2015 1:46 AM, Sean Kanaley wrote:
>
>  Just comment out #:data and append it to the url:
>
>   (http-sendrecv "maps.googleapis.com"
>(string-append
> "http://maps.googleapis.com/maps/api/geocode/json?";
> <http://maps.googleapis.com/maps/api/geocode/json> form-data)
>;#:ssl? ssl?
>;#:port port
>#:version #"1.1"
>#:method  #"GET"
>#:headers (list "Content-Type:
> application/x-www-form-urlencoded")
>;#:data form-data
>;#:content-decode decodes
>))
>
>
> Doesn't work - I get the same error back:
>   blah, blah ... Your client has issued a malformed or illegal request.
> That’s all we know 
>
> I've tried appending the data as you suggest.  I've tried adding "?"
> deliberately to the URI.  I've tried with and without #:headers.  #:version
> #"1.0" and #"1.1".  #:method #"GET" vs #"POST".  Everything produces the
> same error.
>
> But perversely the result of (string-append
> "http://maps.googleapis.com/maps/api/geocode/json?";
> <http://maps.googleapis.com/maps/api/geocode/json> form-data) works if I
> paste it into a browser.
>
> George
>
>
>
>  On Mon, Apr 20, 2015 at 8:37 PM, George Neuner 
> wrote:
>
>>  Hi all,
>>
>> I'm having trouble accessing the Google geocode API using http-sendrecv.
>>
>> Code is:
>>
>> (define (lookup address)
>>   (let [
>> (form-data  (alist->form-urlencoded
>>  (list (cons 'address address)
>>)))
>>
>> (response #f)
>> (lat  #f)
>> (long #f)
>>]
>>
>> (printf "Looking up ~s~n" address)
>> (printf "=> ~s~n" form-data)
>>
>> (with-handlers [
>> (exn:fail?
>>  (lambda (e)
>>(fprintf (ferr) "~n~n%%~n~a~n%%~n" (format "Error:
>> ~a" (exn-message e)))
>>))
>>]
>>   (let-values [
>>((errcode header port)
>> (http-sendrecv "maps.googleapis.com"
>>
>> "http://maps.googleapis.com/maps/api/geocode/json";
>> <http://maps.googleapis.com/maps/api/geocode/json>
&

Re: [racket-users] http-sendrecv with Google geocode

2015-04-20 Thread Sean Kanaley
Just comment out #:data and append it to the url:

 (http-sendrecv "maps.googleapis.com"
   (string-append
"http://maps.googleapis.com/maps/api/geocode/json?";
 form-data)
   ;#:ssl? ssl?
   ;#:port port
   #:version #"1.1"
   #:method  #"GET"
   #:headers (list "Content-Type:
application/x-www-form-urlencoded")
   ;#:data form-data
   ;#:content-decode decodes
   ))

On Mon, Apr 20, 2015 at 8:37 PM, George Neuner  wrote:

>  Hi all,
>
> I'm having trouble accessing the Google geocode API using http-sendrecv.
>
> Code is:
>
> (define (lookup address)
>   (let [
> (form-data  (alist->form-urlencoded
>  (list (cons 'address address)
>)))
>
> (response #f)
> (lat  #f)
> (long #f)
>]
>
> (printf "Looking up ~s~n" address)
> (printf "=> ~s~n" form-data)
>
> (with-handlers [
> (exn:fail?
>  (lambda (e)
>(fprintf (ferr) "~n~n%%~n~a~n%%~n" (format "Error:
> ~a" (exn-message e)))
>))
>]
>   (let-values [
>((errcode header port)
> (http-sendrecv "maps.googleapis.com"
>
> "http://maps.googleapis.com/maps/api/geocode/json";
> 
>;#:ssl? ssl?
>;#:port port
>#:version #"1.1"
>#:method  #"GET"
>#:headers (list "Content-Type:
> application/x-www-form-urlencoded")
>#:data form-data
>;#:content-decode decodes
>))
>   ]
> (set! response (port->string port))
> ;(set! response (read-json port))
> (printf "=> ~s~n" response)
> ))
>
> (fprintf (ferr) "lat:~s long:~s~n"  lat long )
> (values lat long)
> ))
>
> It doesn't yet extract relevant data because I haven't yet successfully
> gotten any data.  8-(
>
>
> As a test I lookup the State House in Boston:
>
>(lookup "24 Beacon St, Boston, MA, 01233")
>
> Looking up "24 Beacon St, Boston, MA, 01233"
> => "address=24+Beacon+St%2C+Boston%2C+MA%2C+01233"
> => "\n\n  \n   name=viewport content=\"initial-scale=1, minimum-scale=1,
> width=device-width\">\n  Error 400 (Bad Request)!!1\n
> \n*{margin:0;padding:0}html,code{font:15px/22px
> arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7%
> auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* >
> body{background:url(//www.google.com/images/errors/robot.png) 100% 5px
> no-repeat;padding-right:205px}p{margin:11px 0
> 22px;overflow:hidden}ins{color:#777;text-decoration:none}a
> img{border:0}@media screen and
> (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//
> www.google.com/images/errors/logo_sm_2.png) no-repeat}@media only screen
> and (min-resolution:192dpi){#logo{background:url(//
> www.google.com/images/errors/logo_sm_2_hr.png) no-repeat 0% 0%/100%
> 100%;-moz-border-image:url(//www.google.com/images/errors/logo_sm_2_hr.png)
> 0}}@media only screen and
> (-webkit-min-device-pixel-ratio:2){#logo{background:url(//
> www.google.com/images/errors/logo_sm_2_hr.png)
> no-repeat;-webkit-background-size:100%
> 100%}}#logo{display:inline-block;height:55px;width:150px}\n  \n   href=//www.google.com/>\n
> 400. That’s an error.\n  Your client has issued a
> malformed or illegal request.  That’s all we know.\n"
> lat:#f long:#f
> #f
> #f
>
> Totally unhelpful.
> However if I paste the URI and urlencoded data into a browser:
>
>
> http://maps.googleapis.com/maps/api/geocode/json?address=24+Beacon+St%2C+Boston%2C+MA%2C+01233
>
> then I get a good return.  It also works from an HTML form, e.g.,
>
>   http://maps.googleapis.com/maps/api/geocode/json";
>  method="GET">
>  address
>  
>  
>  GEOCODE
>  
>   
>
>
> I'm using http-sendrecv successfully with other web APIs - I just can't
> figure out what I'm doing wrong with Google.  Number and/or frequency of
> requests is not an issue - I'm very far from the daily limit and many
> minutes elapse between tests as I'm trying to figure out what's wrong.
>
> The documentation is at
> https://developers.google.com/maps/documentation/geocoding/#GeocodingRequests
>
> Any clues to pierce the veil of stupidity would be appreciated.
> Than

Re: [racket-users] carmack s-expression tweet

2015-03-27 Thread Sean Kanaley
Couldn't this binary s-expression just be a struct?

'(move 3 5)

becomes

(struct move (x y) #:prefab)
(move 3 5)

client/server will likely have some kind of matching either way, and prefab
structs can be matched

(match command
  [(list 'move x y) ...

becomes

(match command
  [(move x y) ...

On Fri, Mar 27, 2015 at 7:15 PM, Alexis King  wrote:

> It might be interesting to create a binary s-expression format for more
> efficient reading/writing, a la BSON’s relationship to JSON. Perhaps even
> with some sort of optional compression. Racket’s reader is fairly
> complicated, though, so it might need to restrict itself to a useful subset?
>
> > On Mar 27, 2015, at 16:12, John Carmack  wrote:
> >
> > On Friday, March 27, 2015 at 2:45:00 PM UTC-5, Brian Craft wrote:
> >> Was this a reference to a particular racket lib? And if so, which one?
> >>
> >> https://twitter.com/ID_AA_Carmack/status/577878167542734848
> >
> > I have a long history of bit packing multiplayer network messages, but
> for this project I am just sending text s-expressions with read and write,
> and my life is much better.  Yes, it is bulkier, but I'm sending binary
> VoIP data after it, so it won't dominate bandwidth, and making software
> easier to write and more reliable is a fine way to spend some of our wealth
> of resources today.
> >
> > --
> > You received this message because you are subscribed to the Google
> Groups "Racket Users" group.
> > To unsubscribe from this group and stop receiving emails from it, send
> an email to racket-users+unsubscr...@googlegroups.com.
> > For more options, visit https://groups.google.com/d/optout.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Racket Users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to racket-users+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [racket] Looking for better designs to learn principles.

2015-03-15 Thread Sean Kanaley
Ah, I should've said that performance is not ideal with either compose (or
thrush), since they build the entire e.g. 10 million long function chain
before calling it, so tail-recursive variants below

(define (iterate f n x)
  (for/fold ([x x])
([i n])
(f x)))

or with the thread-through thingy

(define (iterate f n x)
  (for/fold ([x x])
([i n])
(~> x f)))

With 128 MB default, DrRacket even ran out of memory with my compose
variant. Sorry!


On Sat, Mar 14, 2015 at 6:41 PM, Alexis King  wrote:

> There’s also the thrush function from the point-free package, which uses
> the argument order of the threading macro while providing the functional
> style of compose.
>
>
> http://pkg-build.racket-lang.org/doc/point-free/index.html?q=thrush#%28def._%28%28lib._point-free%2Fmain..rkt%29._thrush%29%29
> <http://pkg-build.racket-lang.org/doc/point-free/index.html?q=thrush#(def._((lib._point-free/main..rkt)._thrush))>
>
> On Mar 14, 2015, at 15:35, Sean Kanaley  wrote:
>
> If "thread-through macro" refers to "
> http://www.greghendershott.com/2013/05/the-threading-macro.html"; then I
> recommend a functional alternative called "compose":
>
> (define print/cdr
>   (match-lambda
> [(cons x xs) (print x) xs]))
>
> (define print-two
>   (compose print/cdr print/cdr))
>
> The result is chained through naturally since the input and output type of
> the lower level function are equal.
>
> For any number of printings
>
> (define (print-n n)
>   (for/fold ([print-n identity])
> ([i n])
> (compose print/cdr print-n)))
>
> (define print-two (print-n 2))
>
> And for any number of anythings
>
> (define (iterate f n)
>   (for/fold ([chain identity])
> ([i n])
> (compose f chain)))
>
> (define print-two (iterate print/cdr 2))
>
>
> On Thu, Mar 12, 2015 at 2:25 PM, Don Green 
> wrote:
>
>> ;Design A:
>> ;Rating: 1 out of 10
>> ;Poor because it uses set!
>> (define print-two
>>   (lambda (f)
>>(print (first f))
>>(set! f (rest f))
>>(print (first f))
>>(set! f (rest f))
>>f))
>>
>> (void (print-two '(1 2))) ;=> 12
>> ;-
>> ;Design B:
>> ;Rating: 2 out of 10
>> ;Better because it nests expressions to avoid using set!
>> ;Poor because it less readable.
>> (define print-two
>>   (lambda (f)
>> (print (first f))
>> (print (first (rest f)))
>> f))
>>
>> (void (print-two '(1 2))) ;=> 12
>> When called in situations that allow one expression only, enclose call
>> within a 'begin' expression.
>> ;-
>> ;Design C:
>> ;Rating: 3 out of 10
>> ;Is this an even better design because it is more readable than nesting
>> expressions as in Design B above?
>> (define (print-two f)
>>   (let* ([_ (print (first f))]
>>  [f (rest f)]
>>  [_ (print (first f))]
>>  [f (rest f)])
>> f))
>> (void (print-two '(1 2))) ;=> 12
>> ;-
>> My questions are:
>> "Can you recommend a better method?"
>> "Can you recommend a better method using 'define with lambda'?"
>> "Does your better method use a macro?"
>> "Does your better method use a thread-through macro?"  If so, could you
>> please provide the definition of the thread-through macro.
>> THANKS!
>>
>>
>> 
>>   Racket Users list:
>>   http://lists.racket-lang.org/users
>>
>>
> 
>  Racket Users list:
>  http://lists.racket-lang.org/users
>
>
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Looking for better designs to learn principles.

2015-03-14 Thread Sean Kanaley
If "thread-through macro" refers to "
http://www.greghendershott.com/2013/05/the-threading-macro.html"; then I
recommend a functional alternative called "compose":

(define print/cdr
  (match-lambda
[(cons x xs) (print x) xs]))

(define print-two
  (compose print/cdr print/cdr))

The result is chained through naturally since the input and output type of
the lower level function are equal.

For any number of printings

(define (print-n n)
  (for/fold ([print-n identity])
([i n])
(compose print/cdr print-n)))

(define print-two (print-n 2))

And for any number of anythings

(define (iterate f n)
  (for/fold ([chain identity])
([i n])
(compose f chain)))

(define print-two (iterate print/cdr 2))


On Thu, Mar 12, 2015 at 2:25 PM, Don Green 
wrote:

> ;Design A:
> ;Rating: 1 out of 10
> ;Poor because it uses set!
> (define print-two
>   (lambda (f)
>(print (first f))
>(set! f (rest f))
>(print (first f))
>(set! f (rest f))
>f))
>
> (void (print-two '(1 2))) ;=> 12
> ;-
> ;Design B:
> ;Rating: 2 out of 10
> ;Better because it nests expressions to avoid using set!
> ;Poor because it less readable.
> (define print-two
>   (lambda (f)
> (print (first f))
> (print (first (rest f)))
> f))
>
> (void (print-two '(1 2))) ;=> 12
> When called in situations that allow one expression only, enclose call
> within a 'begin' expression.
> ;-
> ;Design C:
> ;Rating: 3 out of 10
> ;Is this an even better design because it is more readable than nesting
> expressions as in Design B above?
> (define (print-two f)
>   (let* ([_ (print (first f))]
>  [f (rest f)]
>  [_ (print (first f))]
>  [f (rest f)])
> f))
> (void (print-two '(1 2))) ;=> 12
> ;-
> My questions are:
> "Can you recommend a better method?"
> "Can you recommend a better method using 'define with lambda'?"
> "Does your better method use a macro?"
> "Does your better method use a thread-through macro?"  If so, could you
> please provide the definition of the thread-through macro.
> THANKS!
>
>
> 
>   Racket Users list:
>   http://lists.racket-lang.org/users
>
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Racket DB Library, data conversion

2015-02-14 Thread Sean Kanaley
Nevermind, that seems to be what prepared statements do.

On Sat, Feb 14, 2015 at 9:34 AM, Sean Kanaley  wrote:

> Hello All,
>
> I would like to query based on an incoming hash (with help of json
> library), but I don't see a built-in way to generate query needed. There is
> a rows->dict but I don't see either a dict->where-clause or at least
> whatever query uses in that dollar sign magic to convert
> Racket-val->SQL-string.
>
> Currently I have a function which takes a hash and makes "=$1
>  =$2..." so I can then do something like (apply query  above string>  string>). It would be nice and probably more efficient if the value could
> just be spliced in while I build the string to begin with, but it seems
> like only query has such dollar sign conversion power available.
>
> Am I missing something?
>

  Racket Users list:
  http://lists.racket-lang.org/users


[racket] Racket DB Library, data conversion

2015-02-14 Thread Sean Kanaley
Hello All,

I would like to query based on an incoming hash (with help of json
library), but I don't see a built-in way to generate query needed. There is
a rows->dict but I don't see either a dict->where-clause or at least
whatever query uses in that dollar sign magic to convert
Racket-val->SQL-string.

Currently I have a function which takes a hash and makes "=$1
 =$2..." so I can then do something like (apply query  ). It would be nice and probably more efficient if the value could
just be spliced in while I build the string to begin with, but it seems
like only query has such dollar sign conversion power available.

Am I missing something?

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Little Schemer, lat?

2015-01-08 Thread Sean Kanaley
As I see it, '() may not specifically be a lat, but it's not *not* a lat.
not not == is

Perhaps with a 3rd logical value we could declare it a "maybe" lat. That's
the same answer I would put in the truth table for implication

T T -> T
T F -> F
F T -> Maybe
F F -> Maybe

I know there are alternative logical systems, but I don't actually know any
of them, so sorry to all mathematicians I may have offended with the above.

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Void expression found

2015-01-05 Thread Sean Kanaley
I see "void" as a tangible value specifying no information, whereas
"undefined" is literally no information. So void is more like an empty
universe and undefined is no universe at all.

On Mon, Jan 5, 2015 at 5:40 PM, Vincent St-Amour 
wrote:

> At Mon, 5 Jan 2015 23:20:54 +0100,
> Jos Koot wrote:
> >
> > Off topic:
> > For me the unanswered question remains:
> > Does the vacuum exist or does it not exist?
> > I don't know.
>
> Parmenides had something to say on the matter:
> http://en.wikipedia.org/wiki/Parmenides#The_Way_of_Truth
>
> Vincent
> 
>   Racket Users list:
>   http://lists.racket-lang.org/users
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] universe program using 100% cpu on Mac (also poor Raspberry Pi performance)

2014-12-30 Thread Sean Kanaley
Hi Darren,

I think there are three common kinds of unit tests --

1. Interaction window while developing the function, to ensure it seems to
do what you think it does. It's probably simple yet covers the majority of
cases. These might be copy and pasted into unit tests as a simple sanity
check for basically no extra effort.

2. Corner case checks. The ones you have to go out of your way to think
about. I'm sure there's differing opinions here, but these can be left out
until a bug is revealed, saving you the time of effectively presenting a
proof by exhaustion for every atom of code you write.

3. Redundant checks like you said, e.g. pressing left does in fact make it
go left. My view on this is you don't actually write these as part of the
initial development, because not only is the redundancy clear in short
functions, but the test is going to be subject to the same lazy copy paste
errors that the function is, possibly resulting in functioning but wrong
unit tests (ouch). Where these are helpful is when you refactor. When your
program is complete, but you decide to change the features, and as a result
may want to modify the movement logic, these *formerly* redundant tests now
serve as the sole specification for what your program must continue doing,
regardless of how much you butcher the code. In a way it's like you saved a
backup copy of the code, except in such a way that running it allows the
compiler to find differences in the code for you. But you don't really need
the trouble of a backup copy at the beginning of development (where you may
end up deleting a function altogether!).

On Mon, Dec 29, 2014 at 11:28 PM, Darren Cruse 
wrote:

> Hi Matthias just saw your reply.
>
> Regarding the tests I like what you said about "for a large function -- a
> reader quickly gets the idea of how the function works from reading some
> tests".
>
> But if I'm honest the example that you gave is the kind of example that
> bothers me - in that it's *not* a large function.  The test you gave
> reminds me of the majority that I see - and it struck me recently I think
> what bothers me is that such tests are in effect a tautology
> 
>
> i.e. most of these tests like this, esp. since they are written by the
> same programmer writing the function under test, are literally just a
> restating of the exact same assumptions the programmer has made in writing
> the function.  So they are *literally* redundant.  Yet they must be
> maintained as the programmer maintains and modifies the code going
> forward.  So there is a cost to them, but to me I honestly don't see much
> if any benefit.
>
> Which isn't to say that good tests can't be written if they are testing a
> large and complex function (as you said).  What I question is the common
> belief nowadays that they're always of value even in simple cases.
>
> Anyway hope you'll forgive my heresy.  I turned 50 this year maybe I just
> an old dog now too set in his ways.  I know I'm very much in the minority
> in this view.  No offense intended.
>
> But more to the point - here's what I did while I should have been writing
> tests:
>
> pong-world.rkt via whalesong
> 
> :)
>
> The biggest challenge - other than what looks like some problems with
> multiple/deeply nested overlay/place-image positioning, is that whalesong
> seems to not support "on-release", so for now this works best if you click
> and hold where it says "hit space to serve" and then you can use your mouse
> and play the game against yourself.
>
> This was done using the soegaard/whalesong
>  version of whalesong btw.
>
> Darren
>
>
>
>
> On Mon, Dec 29, 2014 at 8:00 PM, Matthias Felleisen 
> wrote:
>
>>
>> TESTS: Say I want to eliminate a common pattern from your handle-key-down
>> function. If it comes with some tests, four to be precise, a simple run --
>> without playing -- assures me of basic qualities. If you express tests like
>> those below and you formulate them first, you get an idea of how to code
>> the function. And -- for a large function -- a reader quickly gets the idea
>> of how the function works from reading some tests.
>>
>> (check-expect (handle-key-down initial-state "w")  (set-left-moving
>> initial-state UP-DIR))
>>
>> (define (handle-key-down world a-key)
>>   (cond
>> [(key=? a-key "w") (set-left-moving world UP-DIR)]
>> [(key=? a-key "s") (set-left-moving world DOWN-DIR)]
>> [(key=? a-key "up") (set-right-moving world UP-DIR)]
>> [(key=? a-key "down") (set-right-moving world DOWN-DIR)]
>> [else world]))
>>
>> (define (set-left-moving world dir)
>>   (set-left-paddle world (set-paddle-moving (pong-world-left-paddle
>> world) dir PADDLE-SPEED)))
>>
>> (define (set-right-moving world dir)
>>   (set-right-paddle world (set-paddle-moving (pong-world-right-pad

Re: [racket] LINQ

2014-12-14 Thread Sean Kanaley
Michael,

I do mean that more or less, but using them directly is slow. Nested maps /
cartesian on large data sets tries my patience.

John,

Yeah I'd love to do this as a side project but the end result would
probably be lacking without a lot of effort. If I end up needing this a lot
maybe it will happen.

There's a Haskell implementation I haven't looked at yet that I might be
able to translate with lazy Racket.

On Sat, Dec 13, 2014 at 11:58 PM, John Clements 
wrote:
>
>
> On Dec 13, 2014, at 4:45 PM, Sean Kanaley  wrote:
>
> > Hello all,
> >
> > Does anybody know of a workable LINQ for Racket? I'm basically looking
> to run selects and joins on CSV files.
> >
> > If not, any roadblocks people have encountered toying with such a thing?
>
> Ooh, that would be nifty.
>
> I would imagine that doing a good job would require quite a bit of
> database domain knowledge—I know just enough to know that it would be easy
> and fun to do a really bad job.
>
> John
>
>

  Racket Users list:
  http://lists.racket-lang.org/users


[racket] LINQ

2014-12-13 Thread Sean Kanaley
Hello all,

Does anybody know of a workable LINQ for Racket? I'm basically looking to
run selects and joins on CSV files.

If not, any roadblocks people have encountered toying with such a thing?

Sean

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] confused beginner

2014-10-04 Thread Sean Kanaley
You can add this repository to get a more recent version *ppa:plt/racket*


*https://launchpad.net/~plt/+archive/ubuntu/racket
*

On Sat, Oct 4, 2014 at 4:16 PM, Andrew Ulrich  wrote:

> That was the problem, thanks Robby!  I guess ubuntu's apt repo's not up to
> date or something.
>
> Andrew
>
> On Sat, Oct 4, 2014 at 2:38 PM, Robby Findler  > wrote:
>
>> Are you sure you have a recent version of racket? I wonder if you're
>> looking at the docs for the latest release (on docs.racket-lang.org)
>> but you have an older release where you're trying things out.
>>
>> Note that you can look at your local docs and those docs should match
>> up to your local installation.
>>
>> Robby
>>
>>
>> On Sat, Oct 4, 2014 at 2:32 PM, Andrew Ulrich
>>  wrote:
>> > Ok, I'm stuck again:
>> > I'm trying to use place-image, but it keeps saying
>> > place-images: unbound identifier in module in: place-images
>> >
>> > It doesn't even seem to work with the example code in the docs found at:
>> >
>> http://docs.racket-lang.org/teachpack/2htdpimage.html?q=overlay#%28def._%28%28lib._2htdp%2Fimage..rkt%29._place-images%29%29
>> >
>> > Here's what I think the docs say the code is:
>> > #lang racket
>> > (require 2htdp/universe)
>> > (require 2htdp/image)
>> > (require lang/posn)
>> > (place-images
>> >(list (circle 4 "solid" "blue")
>> >  (circle 4 "solid" "white")
>> >  (circle 4 "solid" "white")
>> >  (circle 4 "solid" "white"))
>> >(list (make-posn 18 20)
>> >  (make-posn 0 6)
>> >  (make-posn 14 2)
>> >  (make-posn 8 14))
>> >(rectangle 24 24 "solid" "goldenrod"))
>> >
>> > But like I said, I get the error.  I'm trying to use place-images to
>> place a
>> > bunch of sprite images on a scene for a simple video game.  I'm assuming
>> > place-images the best way to do that.
>> >
>> > Thanks in advance for helping me out.  I know it's basic stuff.
>> >
>> > On Sat, Oct 4, 2014 at 9:04 AM, Andrew Ulrich
>> >  wrote:
>> >>
>> >> Aha, great! Thanks guys!
>> >>
>> >> Andrew
>> >>
>> >> On Sat, Oct 4, 2014 at 8:54 AM, Jens Axel Søgaard <
>> jensa...@soegaard.net>
>> >> wrote:
>> >>>
>> >>> Hi Andrew,
>> >>>
>> >>> To add what Matthias say, if you need a "function version" of bitmap,
>> >>> you can use bitmap/file instead.
>> >>>
>> >>> (require 2htdp/image)
>> >>> (define path-stringy "images/some.png")
>> >>> (bitmap/file path-stringy)
>> >>>
>> >>> Note that I changed (path-stringy) to path-stringy.
>> >>>
>> >>> /Jens Axel
>> >>>
>> >>>
>> >>>
>> >>>
>> >>> 2014-10-04 15:48 GMT+02:00 Matthias Felleisen :
>> >>> >
>> >>> > What you used is called a "computed string" that is, you expect
>> bitmap
>> >>> > to evaluate the argument path-stringy to a string.
>> >>> >
>> >>> > But, in BSL, bitmap expects to be handed a literal string constant
>> (or
>> >>> > a module path):
>> >>> >
>> >>> >
>> -
>> >>> > (require 2htdp/image)
>> >>> >
>> >>> > ;; with a module path
>> >>> > (bitmap 2htdp/planetcute/character-cat-girl.png)
>> >>> >
>> >>> > ;; with a fixed string
>> >>> > (bitmap
>> >>> >
>> "plt/pkgs/htdp-pkgs/htdp-lib/2htdp/planetcute/character-cat-girl.png")
>> >>> >
>> -
>> >>> >
>> >>> > Both of these will succeed and retrieve the cat girl from the Planet
>> >>> > Cute collection that comes with Racket -- Matthias
>> >>> >
>> >>> >
>> >>> >
>> >>> >
>> >>> > On Oct 4, 2014, at 9:36 AM, Andrew Ulrich wrote:
>> >>> >
>> >>> >> Hi, I've got a really simple problem, I think.  Why is it that
>> when I
>> >>> >> try to do the following:
>> >>> >>
>> >>> >> (require 2htdp/image)
>> >>> >> (define path-stringy "images/some.png")
>> >>> >> (bitmap (path-stringy))
>> >>> >>
>> >>> >> I get the following error:
>> >>> >>  bitmap: expected the argument to specify a local path (via a
>> string)
>> >>> >> or a module path (e.g. `icons/b-run.png') in: (bitmap
>> (path-stringy))
>> >>> >>
>> >>> >> I mean, shouldn't path-stringy evaluate to a string before it's
>> passed
>> >>> >> into bitmap?  If not, then how do I use bitmap for anything
>> dynamic?
>> >>> >>
>> >>> >> Thanks,
>> >>> >> Andrew
>> >>> >> 
>> >>> >>  Racket Users list:
>> >>> >>  http://lists.racket-lang.org/users
>> >>> >
>> >>> >
>> >>> > 
>> >>> >   Racket Users list:
>> >>> >   http://lists.racket-lang.org/users
>> >>>
>> >>>
>> >>>
>> >>> --
>> >>> --
>> >>> Jens Axel Søgaard
>> >>
>> >>
>> >
>> >
>> > 
>> >   Racket Users list:
>> >   http://lists.racket-lang.org/users
>> >
>>
>
>
> 
>   Racket Users list:
>   http://lists.racket-lang.org/users
>
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Code that double checks is good, bad, other?

2014-10-04 Thread Sean Kanaley
What do you mean by "weaken" in #3? I presume you mean use a more general
type. Is this to allow for flexibility in future iterations? Promising
any/c instead of void? ?

On Sat, Oct 4, 2014 at 3:04 PM, Matthias Felleisen 
wrote:

>
> Here is an answer that's not a book but it should be one.
>
> 1. If you write an exported function that looks like this:
>
> (define (workhorse x)
>   (validate
> validate
>  validate
>   validate x ...)
>   (compute with x ...))
>
> I recommend that you factor out the validation into a contract:
>
> (provide
>   (contract-out
>(->i ([x (lambda (x)
>   (validate
> validate
>  validate
>validate x ...))])
>...)
>
> (define (workhorse x)
>   (compute with x ...)
>
> It is extremely likely that whoever uses workhorse needs to know about
> these checks, because they are a part of the interface. Put them there, and
> only there.
>
> 2. If you are working on a chain of module and except for the top and
> bottom one, none has contact with the external world, validate values that
> flow thru the chain once: on the way in or out. Skip checks everywhere else.
>
> 3. For the top and bottom value, write the contracts that you want (for
> the supplier) and weaken the contract that you promise (the client) and in
> between trust yourself.
>
> 4. If you have a type system, use it instead of 3. As Neil says, you get
> some of these checks for free (during compile time) so do them.
>
> -- Matthias
>
>
>
>
>
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Code that double checks is good, bad, other?

2014-10-03 Thread Sean Kanaley
The open-endedness of this led me to write a bit, then read a few things,
then produce unnecessarily long responses, and so on, so I deleted
everything to spare people. I'll go with saying thanks for the input.

But here's an interesting related link:

http://blog.codinghorror.com/gold-plating/

Related because more general than double checking is any sort of code
changes that have (should have) no effect (refactoring). My OCD nature is
the cause of this thread. Are there acceptable shortcuts anywhere?
According to Neil's second paragraph, yes.

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Code that double checks is good, bad, other?

2014-10-03 Thread Sean Kanaley
"the problem is when you re-work the code, do you know for sure that
you moved the contract/assertion/validation/checking appropriately."

That's the real crux that I forgot to say. I was inspired to post when I
was slightly repurposing a mid-level function and realized it no longer had
to do as much, then trying to remember if it was used somewhere else where
that functionality was still needed. I *have* been writing more tests
recently. If the function never fails, it doesn't matter that it "could
have" failed if used elsewhere. So perhaps the answer is just lots and lots
of tests and less manual effort.

On Fri, Oct 3, 2014 at 1:28 PM, Raoul Duke  wrote:

> in theory only the "top level" things should validate. by which i mean
> those things which get input from something other than your own code.
>
> the problem is when you re-work the code, do you know for sure that
> you moved the contract/assertion/validation/checking appropriately.
>
> test coverage can help there, in the absence of some AI looking over
> your shoulder for you.
> 
>   Racket Users list:
>   http://lists.racket-lang.org/users
>

  Racket Users list:
  http://lists.racket-lang.org/users


[racket] Code that double checks is good, bad, other?

2014-10-03 Thread Sean Kanaley
Hello all,

Sometimes I run into situations where a callee has certain input
constraints that the caller must satisfy. Particularly when the caller is
just below the user interface level, this can lead to redundant checks. For
example, if the the callee takes an integer, and the user input function
pulls from a control that only accepts integers to begin with, there is
really no need for the caller to validate that the thing received from the
control is really an integer before calling the callee with it. It's this
middle function between UI and underlying low level model function that
seems to have redundancy. Actually, the callee wouldn't have to verify
either, but the callee would be used elsewhere where there might be no
guarantee.

An analogy is the water company should put water into the system, and water
should be verified at the tap before blinding drinking it, but does every
piece of underground pipe need to be like "yep it's water"?

The answer is seemingly "no".

But then it's an issue in a larger program of refactoring every bit of code
to take maximum advantage of every statically-guaranteed piece of
information, running as unsafe-yet-still-safe as possible. That seems like
a lot of manual effort that can be avoided by just throwing in what may or
may not be a redundant check depending on which series of pipes the
information flows through.

So as a practical matter, it's an issue of catching errors (bugs) as soon
as possible vs. there aren't supposed to be any bugs to begin with. So one
can argue that either 1. I don't understand my program well enough or 2.
bigger programs are hard to understand, and some measure of practicality is
warranted. Perhaps the question is more philosophical in the end...is it
better to have something quickly and useful that works 99% of the time, or
a perfect guarantee but potentially longer development time? The answer
depends on whether it's for weapon systems guidance or a hello world
example.

This question is probably more fit for stack-X, but I wonder what the
Racket people think of "excessive" checks.

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] macro question

2014-10-02 Thread Sean Kanaley
(let ([x y])
  x)
=> y

That "let" is just a wrapper that equals y. So your macro is really

(define-syntax (mylet stx)
  (syntax-case stx ()
[(_ x) #'x]
[(_ x xs ...) #'(cons x (mylet xs ...))])])

Which causes
(mylet 1 2 3) => '(1 2 . 3) ;don't forget the dot!

And that's just the macro version of a normal recursive function

(define (mylet . xs)
  (match xs
[(list x) x]
[(list x xs ...) (cons x (apply mylet xs))]))

So nothing macro-y has really taken place. If you are attempting to
redefine let, you'll have to place any binding forms inside of the output
syntax, right of the sharp quote. The runtime code that the macro expands
into has to bind something, in other words. Your original version binds a
value during the expansion of the output code, where the output code is
just the function I have above. I hope that makes sense.


On Thu, Oct 2, 2014 at 9:19 PM, Kevin Forchione  wrote:

> Hi guys,
> Why does this appear to work? I assume it’s not a recommended approach.
>
> #lang racket
>
> (require (for-syntax syntax/parse))
>
> (define-syntax (mylet stx)
>   (let ([val (syntax-case stx ()
>[(_ x) #'x]
>[(_ x xs ...) #'(cons x (mylet xs ...))])])
> val))
>
> (mylet 1 2 3) => ‘(1 2 3)
>
> -Kevin
> 
>   Racket Users list:
>   http://lists.racket-lang.org/users
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] A beginner's question re drawing on a canvas

2014-10-01 Thread Sean Kanaley
At the risk of sending duplicate information, and you should prefer
Matthias' responses as he is far more experienced, but one idea is to place
all drawing code under the canvas class definition. Then the button
callback should invoke that class' new drawing method. This keeps the
actual drawing code within the canvas which is one of its main purposes.
The button just says "do it".

#lang racket/gui

(define frame (new frame%
   [label "Example"]
   [width 300]
   [height 300]))
(define top-canvas (new (class canvas% (super-new [parent frame])
  (define dc (send this get-dc))

  (define/public (draw-something-else)
(send dc draw-rectangle
  50 50
  80 80))

  (define/override (on-paint)
(send dc draw-rectangle
  0  10   ; Top-left at (0, 10), 10 pixels
down from top-left
  30 10) ; 30 pixels wide and 10 pixels high
(send dc draw-line
  0 0; Start at (0, 0), the top-left
corner
  30 30) ; and draw to (30, 30), the
bottom-right corner
(send dc draw-line
  0 30   ; Start at (0, 30), the
bottom-left corner
  30 0)  ; and draw to (30, 0), the
top-right corner


(define button1 (new button%
 [label "A Box"]
 [parent frame]
 [callback (λ (b e)
 (send top-canvas draw-something-else))]))

(define button2 (new button%
 [label "Erase"]
 [parent frame]
 [callback (λ (b e)
 (send top-canvas refresh))]))

(send frame show #t)

Refresh clears the canvas and the does on-paint again, so on-paint is sort
of your default view.

On Wed, Oct 1, 2014 at 10:16 PM, Chris Wright  wrote:

> Thanks Matthias and Sean
>
> It's often helpful when people asking questions ask them clearly ! :)
> I'll now attempt a clarification...
>
> say I have a button in the window, and when that button is pressed, I want
> to draw on the canvas - and later, another button is pressed, and I might
> want to draw something else somewhere else on the canvas.
>
> I think I'm wanting to get hold of the dc outside of the definition of
> on-paint in the initialisation code
>
> cheers and thanks again
>
> Chris
>
> On 2 October 2014 11:57, Matthias Felleisen  wrote:
>
>>
>> Does this help?
>>
>> #lang racket/gui
>>
>> (define frame
>>   (new frame%
>>[label "Example"]
>>[width 300]
>>[height 300]))
>>
>> (define top-canvas
>>   (new (class canvas%
>>  (inherit get-dc)
>>  (super-new [parent frame])
>>  (define/override (on-paint)
>>(define dc (get-dc))
>>(send dc draw-rectangle
>>  0  10   ; Top-left at (0, 10), 10 pixels down from
>> top-left
>>  30 10) ; 30 pixels wide and 10 pixels high
>>(send dc draw-line
>>  0 0; Start at (0, 0), the top-left corner
>>  30 30) ; and draw to (30, 30), the bottom-right corner
>>(send dc draw-line
>>  0 30   ; Start at (0, 30), the bottom-left corner
>>  30 0)  ; and draw to (30, 0), the top-right corner
>>
>>
>> (send frame show #t)
>>
>>
>>
>>
>> On Oct 1, 2014, at 9:51 PM, Chris Wright wrote:
>>
>> > I would like to draw on a canvas in a window at various times during
>> program execution.
>> > My first attempt was to combine two examples:
>> >
>> > #lang racket/gui
>> >
>> > (define frame (new frame%
>> >[label "Example"]
>> >[width 300]
>> >[height 300]))
>> > (define top-canvas (new canvas% [parent frame]))
>> >
>> > (send frame show #t)
>> >
>> > (define dc (send top-canvas get-dc))
>> >
>> > (send dc draw-rectangle
>> >   0  10   ; Top-left at (0, 10), 10 pixels down from top-left
>> >   30 10) ; 30 pixels wide and 10 pixels high
>> > (send dc draw-line
>> >   0 0; Start at (0, 0), the top-left corner
>> >   30 30) ; and draw to (30, 30), the bottom-right corner
>> > (send dc draw-line
>> >   0 30   ; Start at (0, 30), the bottom-left corner
>> >   30 0)  ; and draw to (30, 0), the top-right corner
>> >
>> >
>> >
>> > The cross and box are drawn, but "instantly" over-written by a blank
>> canvas. I suppose this is because on-paint is triggered? (not sure by
>> what..)
>> > If I put the (send frame...) form at the end of the code, the cross and
>> box aren't seen.
>> >
>> > I am sure this is due to me not understanding the mode

Re: [racket] A beginner's question re drawing on a canvas

2014-10-01 Thread Sean Kanaley
Hi,

Just make the drawing code part of on-paint. I have inlined a subclass for
you:

#lang racket/gui

(define frame (new frame%
   [label "Example"]
   [width 300]
   [height 300]))
(define top-canvas (new (class canvas% (super-new [parent frame])
  (define dc (send this get-dc))

  (define/override (on-paint)
(send dc draw-rectangle
  0  10   ; Top-left at (0, 10), 10 pixels
down from top-left
  30 10) ; 30 pixels wide and 10 pixels high
(send dc draw-line
  0 0; Start at (0, 0), the top-left
corner
  30 30) ; and draw to (30, 30), the
bottom-right corner
(send dc draw-line
  0 30   ; Start at (0, 30), the
bottom-left corner
  30 0)  ; and draw to (30, 0), the
top-right corner


(send frame show #t)

But if you want, you can do something like

(define your-canvas
  (class canvas%
 ... ; as-above after the class canvas% part

Also you can combine commands to a single object with send*

(define/override (on-paint)
(send* dc
  (draw-rectangle
   0  10   ; Top-left at (0, 10), 10 pixels
down from top-left
   30 10) ; 30 pixels wide and 10 pixels high
  (draw-line
   0 0; Start at (0, 0), the top-left corner
   30 30) ; and draw to (30, 30), the
bottom-right corner
  (draw-line
   0 30   ; Start at (0, 30), the bottom-left
corner
   30 0)  ; and draw to (30, 0), the top-right
corner
  )


On Wed, Oct 1, 2014 at 9:51 PM, Chris Wright  wrote:

> I would like to draw on a canvas in a window at various times during
> program execution.
> My first attempt was to combine two examples:
>
> #lang racket/gui
>
> (define frame (new frame%
>[label "Example"]
>[width 300]
>[height 300]))
> (define top-canvas (new canvas% [parent frame]))
>
> (send frame show #t)
>
> (define dc (send top-canvas get-dc))
>
> (send dc draw-rectangle
>   0  10   ; Top-left at (0, 10), 10 pixels down from top-left
>   30 10) ; 30 pixels wide and 10 pixels high
> (send dc draw-line
>   0 0; Start at (0, 0), the top-left corner
>   30 30) ; and draw to (30, 30), the bottom-right corner
> (send dc draw-line
>   0 30   ; Start at (0, 30), the bottom-left corner
>   30 0)  ; and draw to (30, 0), the top-right corner
>
>
>
> The cross and box are drawn, but "instantly" over-written by a blank
> canvas. I suppose this is because on-paint is triggered? (not sure by
> what..)
> If I put the (send frame...) form at the end of the code, the cross and
> box aren't seen.
>
> I am sure this is due to me not understanding the model properly - I'd be
> grateful for some help...
>
> many thanks
>
> Chris
>
> 
>   Racket Users list:
>   http://lists.racket-lang.org/users
>
>

  Racket Users list:
  http://lists.racket-lang.org/users


[racket] DrRacket 6.1 or Hardware Issue?

2014-09-08 Thread Sean Kanaley
After investigating a near complete lock up some more (saved by TTY window
and killing DrRacket after seeing it with 3GB+ residency), it's clearly
correlated with background expansion of an accidentally infinitely looping
macro. A few questions..

1. Is the OS supposed to break and enter an infinite swap loop? If that is
just a fact of life for a program requesting too much memory simultaneously
(and an ever increasing amount), well for example ghc just shuts itself
down claiming "too much memory requested" or something like that.

2. Is this related to my very long time ago issue where I removed a bad 1GB
from the 3rd slot, lazily leaving the 4th slot where it is, causing me to
have 3GB instead of 4, even though it's "supposed to" have 4 based on the
max slot (I have never encountered this sort of system freeze before
however)? Maybe the OS would more gracefully handle the paging?

3. Can DrRacket simply realize it's expanding the same thing and not demand
infinite memory (I don't understand the system on the implementation level,
sorry if that's off base).

The solution, aside from me not writing incorrect macros is to disable
background expansion. Relatedly, DrRacket doesn't seem able to reclaim this
space without being restarted. Closing the file and clicking the garbage
collection thing only recovers say 20MB out of 2GB if I turn off expansion
before the OS locks.

Lastly, a related possible bug I've encountered since 6.1 is the infinite
garbage collection loop, where the OS remains responsive but DrRacket has
to be restarted, but this one I have no idea where it comes from only that
it seems to happen after a while, and fairly reliably so.

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Submodules can't be imported in same file?

2014-09-05 Thread Sean Kanaley
Oh of course, I had inverted the hierarchy of modules. Your way is much
more logical, thanks. I got too sidetracked into what exactly module+
does...


On Fri, Sep 5, 2014 at 6:29 PM, Greg Hendershott 
wrote:

> The following approach works for me. Would that do what you need?
>
> ;; - mod.rkt -
> #lang racket
>
> (module private racket
>   (define (secret)
> 'foo)
>   (provide secret))
>
> (require 'private)
>
> (define (wrapper)
>   (secret))
>
> (provide (all-defined-out))
> ;; Note that all-defined-out will not provide stuff from 'private.
> ;; For that to happen, you would need to use (require (all-from-out
> ;; 'private)). So ... don't do that.
>
>
> ;; - use-mod.rkt -
> #lang racket
>
> (require "mod.rkt")
> (wrapper) ;; => 'foo
> (secret)  ;; => error -- as desired
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Submodules can't be imported in same file?

2014-09-05 Thread Sean Kanaley
(reply to all)
Right but that doesn't work from within the file, only at REPL or another
file.

#lang racket
(module+ invisible
  (provide x)
  (define x 3))

(require (submod "." invisible))

doesn't work

  Racket Users list:
  http://lists.racket-lang.org/users


[racket] Submodules can't be imported in same file?

2014-09-05 Thread Sean Kanaley
Hello,

For ease of exporting wrapper functions I am trying to do something like

#lang racket



(module wrap racket or module+ wrap
  (provide (all-defined-out))
  )

(require 'wrap)
(provide (all-from-out 'wrap))

With (module wrap racket ...), (require 'wrap) works but the stuff to be
wrapped isn't visible in the module, which is what the module+ form is for,
but then there doesn't seem to be a way to require wrap then. It seems to
require REPL or another file using (submod "" wrap).

Obviously I can just split the code into two files in the first place, but
then what was the intended use for modules or submodules vs. just plain
files?

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] performance of iteration through a vector

2014-08-30 Thread Sean Kanaley
The generic (for ([var seq]) is slow regardless of vector/list/etc. But
there is often a specific "in-" form. On my machine

(for ((j (in-range 100)))
(for ((v (in-vector vec)))
  (set! sum (+ sum v

is very slightly faster than the explicit vector ref version, 7.3... vs.
7.6... (32 bit Ubuntu).


On Sat, Aug 30, 2014 at 6:54 PM, Dmitry Pavlov  wrote:

> Hello,
>
> Consider the following program:
>
> (define n 100)
> (define vec (for/vector ((i (in-range n))) i))
>
> (let ((t (current-inexact-milliseconds))
>   (sum 0))
>   (for ((j (in-range 100)))
> (for ((i (in-range n)))
>   (set! sum (+ sum (vector-ref vec i)
>   (displayln (/ (- (current-inexact-milliseconds) t) 1000.0)))
>
> (let ((t (current-inexact-milliseconds))
>   (sum 0))
>   (for ((j (in-range 100)))
> (for ((v vec))
>   (set! sum (+ sum v
>   (displayln (/ (- (current-inexact-milliseconds) t) 1000.0)))
>
>
> On my system (64-bit linux, Racket 6.1.0.2), it gives the following result:
>
> 1.016682861328125
> 6.3261611328125
>
>
> So we can make a conclusion that (for ((v vec)) ...) is
> 6x slower than (for ((i (in-range n))) ... (vector-ref vec i) ...)
> Is it normal? Would you advise to use the explicit (vector-ref)
> when performance matters?
>
> Best regards
>
> Dmitry
>
>
> 
>   Racket Users list:
>   http://lists.racket-lang.org/users
>
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Use of map and eval to evaluate symbol in namespace

2014-08-10 Thread Sean Kanaley
***The ultimate (programming) concern is what will produce the highest
average correct-and-useful-running-program-output per second over my
lifespan.***

(philosophical extensions: provided it doesn't hurt other people, unless
they are "bad", where bad = ...etc...)

Or anyone else who programs. The average decreases when something new is
learned, and increases later as a payoff from the new knowledge
(ideally...). This is especially important to experts in other fields who
want a quick solution instead of a theoretically maximally correct and
beautiful and least upsetting to experts solution.

So I didn't need keyword-apply. I had the following choices:

1. build literal expression, call eval (~1 min dev time)

2. search documentation or google for "apply keyword", reach page of
documentation, *carefully* read all relevant-sounding functions on it,
choose keyword apply, THEN implement it (~10+ min?) (in reality after
trying apply for a bit since it seems like it would work, and for fear of
just using eval and being branded a C programmer, eventually concluding it
can't work = additional 5 min)

3. make a mistake with step 2, make post to user's list asking about this
case, receive feedback that it wasn't necessary to use it, go back and fix
code to be "correct" (unsure of time to type the first post, but the
overall energy spent on this process exceeds #1 and #2 for sure)

In my case, I'm glad I now know about keyword-apply because I will be using
Racket until I die. Those 15 minutes will *hopefully* save over 15 minutes
by the end of my life. They might not though, and time now > time later,
but I'm still glad because I enjoy programming as a hobby and want to be
good at it, but in terms of maximizing output I should have just used eval.

Taken further, there is some optimal level of knowledge that allows for all
tasks that need to be completed to be completed as quickly and accurately
as possible, where further knowledge represents time spent wasted acquiring
it. Professionals in fields other than programming itself will probably
have a low level of optimal knowledge, and the attitude that some seem to
have about "dumb newbies with their dumb evals" is incorrect. They should
possibly do whatever is as fast as possible, regardless of how bad the code
is.

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Use of map and eval to evaluate symbol in namespace

2014-08-09 Thread Sean Kanaley
Sorry, couple typos: mapply = map and l = lst.


On Sat, Aug 9, 2014 at 10:10 AM, Sean Kanaley  wrote:

> There's a simple enough example I think: apply with keyword parameters.
> Apply has that built-in..sort of...but the list is supposed to be provided
> inline to APPLY, seemingly requiring apply to be applied (e.g. (apply apply
> (cons *thefunctiontoapply* params))), except keywords can't be expressions
> anyway. I have a bunch of card definitions for Dominion with many defaults:
>
> (struct card (... actions buys ...))
>
> (define (make-card ... #:actions actions #:buy buys ...)
>   ...)
>
> The non-keyword-requiring way is
>
> (define CARDS
>   (map (\ (lst) (apply make-card lst))
>   '([... 1 1 ...]
>[... 2 0 ...])))
>
> The keyword way is
>
> ;ns is namespace
> (mapply (\ (lst) (eval `(apply make-card ',(car l) ,@(cdr l)) ns))
> '([(...) #:actions 1 #:buys 1 ...]))
>
> Short of making a big macro to take some exact format and get it to work
> with keywords and all that, eval seems to be just what is needed.
>
>
> On Sat, Aug 9, 2014 at 8:27 AM, Neil Van Dyke 
> wrote:
>
>> Sounds like a good rule of thumb.  Two suggestions to add:
>>
>> * Maybe there could also be a second rule of thumb, like, "If you need
>> arbitrary Racket expressions, then consider whether you can do it with one
>> of the following patterns: [list some patterns involving combinations of
>> syntax extension, custom #lang, dynamic requires, considering whether
>> config files can actually be compile-time #lang, etc.]"  This is less
>> important than the first rule of thumb.
>>
>> * When we list typical newbie cases that don't actually require "eval",
>> we can expect that newbie will immediately want an example of the
>> non-"eval" way to do that typical thing.  At the very least, an example
>> showing, say, good use of hashes in parameters, with a sensible thin
>> abstraction layer over it, for that case.  These examples would be tedious
>> to work through and write up well, but someday some knowledgeable and
>> benevolent person will do it.  (I am not this person.  Book royalties
>> aren't enough to ease the pain. I'd rather that newbies just never heard of
>> "eval" or were scared away from it, rather than having to talk them down
>> off the ledge all the time.)
>>
>> Neil V.
>>
>>
>> Eli Barzilay wrote at 08/09/2014 07:31 AM:
>>
>>  I think that I ran into a nice way to discourage eval except when
>>> needed: the rule of thumb is to only use eval when you need to evaluate
>>> any arbitrary (Racket) expression.  It sounds simplistic but it covers
>>> lots of cases that make newbies run to eval:
>>>
>>> * I just want to get the value of a variable whose name is held in x
>>>
>>> * More common: I have a symbol/string that names a function, I just need
>>>to call that function
>>>
>>> * I need to keep an update-able mapping from names to values, just like
>>>what the toplevel does
>>>
>>> * I want to let people write an arithmetic expression instead of a
>>>number
>>>
>>> In such cases questions like "do you need allow calling all functions",
>>> and "do you need to handle lambda expressions" have negative answers.
>>>
>>>
>>>
>>> On Sun, Jul 27, 2014 at 4:16 PM, Neil Van Dyke 
>>> wrote:
>>>
>>>> Maybe there should be a periodic public service announcement about not
>>>> using
>>>> "eval".  This time I will communicate in FAQ format:
>>>>
>>>> Q: How do I use eval?
>>>> A: Don't use eval.
>>>>
>>>> Q: But don't so many academic books feature eval prominently, so doesn't
>>>> that mean I should use try to eval?
>>>> A: Those books use eval for pedagogic reasons, or because the author is
>>>> enamored of some theoretical appeal of eval, or because the author
>>>> wants to
>>>> watch the world burn.  Don't use eval.
>>>>
>>>> Q: But, but, but, I am just starting to learn, and eval seems to do
>>>> what I
>>>> need.
>>>> A: Eval is almost certainly not what you want.  Learn how to use the
>>>> other
>>>> basics effectively.  Don't use eval.
>>>>
>>>> Q: I now am very comfortable with the language, I am aware that I should
>>>> avoid eval in almost all cases, and I can tell you why eval is actually
>>>> the
>>>> right thing in this highly unusual case.
>>>> A: Cool, that's why eval is there.
>>>>
>>>> Neil V.
>>>>
>>>>
>>>>
>> 
>>  Racket Users list:
>>  http://lists.racket-lang.org/users
>>
>
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Use of map and eval to evaluate symbol in namespace

2014-08-09 Thread Sean Kanaley
There's a simple enough example I think: apply with keyword parameters.
Apply has that built-in..sort of...but the list is supposed to be provided
inline to APPLY, seemingly requiring apply to be applied (e.g. (apply apply
(cons *thefunctiontoapply* params))), except keywords can't be expressions
anyway. I have a bunch of card definitions for Dominion with many defaults:

(struct card (... actions buys ...))

(define (make-card ... #:actions actions #:buy buys ...)
  ...)

The non-keyword-requiring way is

(define CARDS
  (map (\ (lst) (apply make-card lst))
  '([... 1 1 ...]
   [... 2 0 ...])))

The keyword way is

;ns is namespace
(mapply (\ (lst) (eval `(apply make-card ',(car l) ,@(cdr l)) ns))
'([(...) #:actions 1 #:buys 1 ...]))

Short of making a big macro to take some exact format and get it to work
with keywords and all that, eval seems to be just what is needed.


On Sat, Aug 9, 2014 at 8:27 AM, Neil Van Dyke  wrote:

> Sounds like a good rule of thumb.  Two suggestions to add:
>
> * Maybe there could also be a second rule of thumb, like, "If you need
> arbitrary Racket expressions, then consider whether you can do it with one
> of the following patterns: [list some patterns involving combinations of
> syntax extension, custom #lang, dynamic requires, considering whether
> config files can actually be compile-time #lang, etc.]"  This is less
> important than the first rule of thumb.
>
> * When we list typical newbie cases that don't actually require "eval", we
> can expect that newbie will immediately want an example of the non-"eval"
> way to do that typical thing.  At the very least, an example showing, say,
> good use of hashes in parameters, with a sensible thin abstraction layer
> over it, for that case.  These examples would be tedious to work through
> and write up well, but someday some knowledgeable and benevolent person
> will do it.  (I am not this person.  Book royalties aren't enough to ease
> the pain. I'd rather that newbies just never heard of "eval" or were scared
> away from it, rather than having to talk them down off the ledge all the
> time.)
>
> Neil V.
>
>
> Eli Barzilay wrote at 08/09/2014 07:31 AM:
>
>  I think that I ran into a nice way to discourage eval except when
>> needed: the rule of thumb is to only use eval when you need to evaluate
>> any arbitrary (Racket) expression.  It sounds simplistic but it covers
>> lots of cases that make newbies run to eval:
>>
>> * I just want to get the value of a variable whose name is held in x
>>
>> * More common: I have a symbol/string that names a function, I just need
>>to call that function
>>
>> * I need to keep an update-able mapping from names to values, just like
>>what the toplevel does
>>
>> * I want to let people write an arithmetic expression instead of a
>>number
>>
>> In such cases questions like "do you need allow calling all functions",
>> and "do you need to handle lambda expressions" have negative answers.
>>
>>
>>
>> On Sun, Jul 27, 2014 at 4:16 PM, Neil Van Dyke 
>> wrote:
>>
>>> Maybe there should be a periodic public service announcement about not
>>> using
>>> "eval".  This time I will communicate in FAQ format:
>>>
>>> Q: How do I use eval?
>>> A: Don't use eval.
>>>
>>> Q: But don't so many academic books feature eval prominently, so doesn't
>>> that mean I should use try to eval?
>>> A: Those books use eval for pedagogic reasons, or because the author is
>>> enamored of some theoretical appeal of eval, or because the author wants
>>> to
>>> watch the world burn.  Don't use eval.
>>>
>>> Q: But, but, but, I am just starting to learn, and eval seems to do what
>>> I
>>> need.
>>> A: Eval is almost certainly not what you want.  Learn how to use the
>>> other
>>> basics effectively.  Don't use eval.
>>>
>>> Q: I now am very comfortable with the language, I am aware that I should
>>> avoid eval in almost all cases, and I can tell you why eval is actually
>>> the
>>> right thing in this highly unusual case.
>>> A: Cool, that's why eval is there.
>>>
>>> Neil V.
>>>
>>>
>>>
> 
>  Racket Users list:
>  http://lists.racket-lang.org/users
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] "error: degrees->complex: 360.0"

2014-05-17 Thread Sean Kanaley
What's wrong with the user parameterizing it like this?  To save you from
having to read the whole thing, it randomly makes digits that belong to
either the integer or fractional portion where the user chooses the max
number of digits to generate.

;ms = "max sig fig count", rs = "rand sig fig count"
(define (random-integer ms [return-len? #f])
  (let ([rs (add1 (random ms))])
(let R ([i rs] [sum 0])
  (if (zero? i)
  (if return-len? (values sum rs) sum)
  (R (sub1 i)
 (+ (* 10 sum) (random 10)))

(define (random-fraction ms)
  (let-values ([(frac-digits len) (random-integer ms #t)])
(/ frac-digits (expt 10 len

(define (random-rational ms)
  (let* ([int-figs (random (add1 ms))]
 [int (if (zero? int-figs)
  0
  (random-integer int-figs))]
 [frac-figs (- ms int-figs)]
 [frac (if (zero? frac-figs)
   0
   (random-fraction frac-figs))])
(+ int frac)))


On Sat, May 17, 2014 at 12:39 AM, Neil Toronto wrote:

> There's a random-real generator in "math/private/utils/flonum-tests.rkt".
> The generator Typed Racket uses is in "tests/typed-racket/random-
> real.rkt".
>
> I haven't settled on a general-purpose real number generator. For flonums
> I usually write something like this:
>
> #lang racket
>
> (require math/base math/flonum)
>
> (define max-ord (flonum->ordinal +max.0))
>
> (define (random-flonum)
>   (define r (random))
>   (cond [(< r 0.025)  +nan.0]
> [(< r 0.050)  +inf.0]
> [(< r 0.075)  -inf.0]
> [(< r 0.100)  -0.0]
> [(< r 0.125)  +0.0]
> [else  (ordinal->flonum (random-integer (- max-ord)
> (+ max-ord 1)))]))
>
> Sometimes I have cases for -max.0, -min.0, +min.0 and +max.0 to test
> near-underflow and near-overflow conditions, or a (- (random) 0.5) or
> similar case to test more typical inputs.
>
> Rationals are a trickier because they're unbounded in both size and
> precision. Probabilistically, they're a weird domain: a uniform probability
> distribution over any given interval of rationals doesn't exist. You can
> get around this by using a fixed precision, but what would you fix it at?
>
> Neil ⊥
>
>
> On 05/13/2014 11:46 AM, Robby Findler wrote:
>
>> Okay, then I'll go with this:
>>
>> (define/contract (angle->proper-range α)
>>(-> real? (between/c 0 360))
>>(let loop ([θ (- α (* 360 (floor (/ α 360])
>>  (cond [(negative? θ) (+ θ 360)]
>>[(>= θ 360)(- θ 360)]
>>[else θ])))
>>
>> Can you point me to your random real number generator, btw?
>>
>> Robby
>>
>>
>> On Tue, May 13, 2014 at 9:06 AM, Neil Toronto 
>> wrote:
>>
>>> I can't get it to take more than on iteration, either. It's there in
>>> case I
>>> missed something. :)
>>>
>>> Neil ⊥
>>>
>>>
>>> On 05/13/2014 05:59 AM, Robby Findler wrote:
>>>
>>>>
>>>> Thanks, Neil!
>>>>
>>>> Why is the loop needed? I can't seem to get it to take more than one
>>>> iteration.
>>>>
>>>> Robby
>>>>
>>>> On Mon, May 12, 2014 at 11:24 PM, Neil Toronto 
>>>> wrote:
>>>>
>>>>>
>>>>> He went with exact rationals. Here's another option, which preserves
>>>>> inexactness:
>>>>>
>>>>>   (define (angle->proper-range α)
>>>>> (let loop ([θ  (- α (* 360 (floor (/ α 360])
>>>>>   (cond [(negative? θ)  (loop (+ θ 360))]
>>>>> [(>= θ 360) (loop (- θ 360))]
>>>>> [else  θ])))
>>>>>
>>>>> Its accuracy drops off outside of about [-1e16,1e16].
>>>>>
>>>>> The fact that this is hard to get right might be good motivation for an
>>>>> `flmodulo` function.
>>>>>
>>>>> Neil ⊥
>>>>>
>>>>>
>>>>> On 05/12/2014 09:49 PM, Sean Kanaley wrote:
>>>>>
>>>>>>
>>>>>>
>>>>>> Interesting, my code has the same bug then.  I called it modulo/real,
>>>>>> used for things like displaying the space ship's rotation to the user
>>>>>> or
>>>>>> wrapping x coordinates to stay in the world.  Apparently it's going to
&

[racket] universe and big-bang initial state

2014-05-13 Thread Sean Kanaley
I am making a server controlled game, where the clients are just
input/outputs to/from the server.  Therefore the clients have no valid
independent initial state.  Is there some way to hold off until the server
handles the incoming connection by sending the initial state to it?
 Otherwise it's pretty much use #f in big-bang and busy wait all the
handlers.

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] "error: degrees->complex: 360.0"

2014-05-12 Thread Sean Kanaley
Interesting, my code has the same bug then.  I called it modulo/real, used
for things like displaying the space ship's rotation to the user or
wrapping x coordinates to stay in the world.  Apparently it's going to fail
at some point with vector ref out of range.  What was your fix?  I was
thinking to just clamp explicitly like mod/real = (max 0 (min
the-mod-minus-1 (old-modulo/real x)))


On Mon, May 12, 2014 at 11:12 PM, Robby Findler  wrote:

> Right. Probably there is a better fix, but the essential problem, as I
> understand it, is that there are more floating points between 0 and 1
> than between any two other integers and the code made the assumption
> that that didn't happen
>
> The basic desire is to turn a real number into a number in [0,360)
> such that the result represents the same number in degrees but is
> normalized somehow.
>
> Robby
>
> On Mon, May 12, 2014 at 10:06 PM, Danny Yoo 
> wrote:
> > Wow.  Floating point really is nasty.  I see how it might have happened
> now.
> >
> > ;;;
> >> -0.0001
> > -1e-16
> >> (+ 360 -1e-16)
> > 360.0
> >>
> > ;;;
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] "error: degrees->complex: 360.0"

2014-05-12 Thread Sean Kanaley
The entire program is too big but some tests:

pass ... (rotate -0.0 SHIP)
pass ... (rotate -0.0001 SHIP)
fail... (rotate -0.0001 SHIP)

  Racket Users list:
  http://lists.racket-lang.org/users


[racket] "error: degrees->complex: 360.0"

2014-05-12 Thread Sean Kanaley
Hello all,

I can't figure this out as I have no function called degrees->complex and
it occurs only sometimes.  It's always when rotating stuff through the
positive x axis, as in it's probably related to floating point operations
like sin or cos near 0 or perhaps integer multiples of 2pi.  So far I
believe it has only happened rotating clockwise where the error freezes the
program with slightly negative radians displaying (part of my debug output).

It's possible it's my own bug with a bad sqrt or using NaN or something,
but then what does the message mean?

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] "lab notebook on learning process" (was: Re: Macros baffle me)

2014-05-05 Thread Sean Kanaley
The question "who is at fault" is not meant as some kind of personal attack
(= emotional is what you meant?) at the "jerk(s)" responsible, but rather
as a question whose answer gives input to selecting the best course of
action.  Since my English isn't working today, in Racket:

;solve-problem : blame-who -> action
(define (alleviate-problem who)
  (case who
[(Racket) (file-bug-report)]
[(me) (stop-being-stupid)]
[else (post-for-clarification)]))

The main use of this is to avoid filing bug reports for my own bugs.


On Mon, May 5, 2014 at 9:59 PM, Hendrik Boom  wrote:

> On Mon, May 05, 2014 at 11:58:17AM -0400, Sean Kanaley wrote:
>
> > So technically it was my fault,
> > but the documentation could benefit from some kind of "WARNING!" section
> on
> > each or at least especially dangerous pages for such pitfalls.  Imagine
> if
> > your car explodes if you have the break depressed while turning the AC
> > dial.  Probably don't want that info on page 87 subsection a.1.c.  But
> > since there's no way to anticipate all potential user bugs, it's not
> really
> > the fault of the documentation writers either.  So who/what is at fault?
>
> A better question that 'who is at fault' would be 'what can be done to
> alleviate the problem'.
>
> I would make it less of an emotional issue.
>
> -- hendrik
> 
>   Racket Users list:
>   http://lists.racket-lang.org/users
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] "lab notebook on learning process"

2014-05-05 Thread Sean Kanaley
I think we just misunderstood each other then.  I was interpreting what you
said in conjunction with what some others said in response, which painted
it in a different light.  And my responses in turn weren't meant to be
overly serious sounding, but mostly just silly stories of my flailing
around in various languages and things that make them difficult or
annoying.  They certainly weren't meant to insult your intelligence.

I'll have to look at Debug.Trace.


On Mon, May 5, 2014 at 2:14 PM, Artyom Kazak  wrote:

> > fellow i-wish-racket-was-as-awesome-as-haskell-ian
>
> But, but I'm not!..
>
> > The issues you have with for/and, etc. is a fundamental issue with strict
> > evaluation vs. either lazy evaluation or no evaluation (macros). One
> > cannot correctly short circuit out of a loop that's already preprocessed
> > every possible result!
>
> I don't have issues with `for/and`; moreover, I do not wish for Racket to
> be
> lazy by default, or uber-functional, or dependently typed, or anything else
> which Haskell or another language is. I understand the tradeoffs. What I
> don't understand is why I seem to be expected to start a discussion about
> those tradeoffs when I simply want to say “here's when lack of laziness
> bites”. I don't intend to make any judgements, and it's a pity that people
> still see them whenever I say anything more emotional than “it is how it
> is”.
>
> > Lastly, without meaning to be rude, as it's coming from the point of view
> > of someone who's had similar issues, there's a degree of RTFM present...
>
> I'll include this whole paragraph verbatim as a disclaimer for the whole
> series, if you don't mind (even tho it's a bit upsetting to see you telling
> me all these obvious things as if there was a chance that I think
> documentation writers are at fault for my misunderstandings and mistakes,
> or
> that I think some of the perceived issues I have with Racket are due to it
> being stupid, or that I want it to be a Haskell clone, or that I'm trying
> to
> learn it a why-isn't-it-Haskell-Racket).
>
> > And thank god, because it would take 15 minutes to insert an impure debug
> > statement.
>
> As per customs and traditions of Internet White Knights, I feel obliged to
> reply that there's Debug.Trace module which makes it a considerably easier
> task (and it's the second result when googling “haskell debug”, too).
>
> > By the way, speed is improved when using the "racket" command-line
> command
> > as opposed to running in DrRacket for whatever reason, especially when
> > using big numbers, by an astounding amount sometimes. I myself recently
> > learned that...
>
> Thanks, noted. (I updated the post.)
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] "lab notebook on learning process" (was: Re: Macros baffle me)

2014-05-05 Thread Sean Kanaley
“don't forget:
call-by-value! call-by-value!” somewhere early on.

Don't feel bad, fellow i-wish-racket-was-as-awesome-as-haskell-ian, I
submitted an incorrect bug report claiming something like
(function-call (const (random))) wasn't passing different random values,
where it was kindly pointed out that call-by-value insures it wouldn't.
 There *is* lazy racket.  The issues you have with for/and, etc. is a
fundamental issue with strict evaluation vs. either lazy evaluation or no
evaluation (macros).  One cannot correctly short circuit out of a loop
that's already preprocessed every possible result!

I had tried to implement Haskell's monoid type class (and type classes in
general), but mappend doesn't work in a strict language. There's no way to
pass the arguments to the Or monoid without evaluating them, and any
macro/thunk-based solution has this restraint propagate outwards.  Anything
calling mappend has to not evaluate its arguments either, or they will be
pre-evaluated before being Or-mappended, e.g. mconcat.  Then I tried it in
lazy racket and couldn't get the macros for the type classes to even
compile.  Something about begin != lazybegin != begin-for-syntax !=
begin-for-lazy-syntax-but-itself-is-strict or who knows...

On the other hand, a few weeks ago I did ICFP 2007 contest for fun in
Haskell.  It took me several hours to fix a "bug" (turned out to be a space
leak) caused by laziness.  It turned out that my flood fill loop was
thunk-ifying a tail recursive function that I had defined with an internal
let.  Using a couple bang patterns changed a minute long wait for "out of
memory" into an efficient loop.  In a real live contest or with real
customers waiting, I imagine using a
who-knows-what's-actually-happening-language carries considerable risk to
the developer...

So there are tradeoffs.  To me, Haskell with its type system (and the
desired overloading) and more uniform evaluation (always lazy instead of
function vs. macro for things like and/or) is the "better" language, but to
be honest I'm not sure I would want my life to depend on making software in
it.  So I find myself using Racket a lot as a usually trustworthy
alternative.  There have been a couple of literally unbelievable bugs, like
in one case where opening a tab in DrRacket changes the results running a
test module in another tab.

At present, my roommate and I are building side-by-side solutions in Visual
Basic and Racket (RESPECTIVELY, thank you).  It's a front-end for a matlab
simulation -- a simple GUI with few complications.  Since that's actually
what basic is good at, the number of lines of code are actually almost the
same, but each new feature I've added in about 1/3 the time, spending the
other 2/3 debugging his:

public sub function (byref dim integer sub1 as ref, byval integer(,) ref as
mouseeventargs of systemeventhandler) as function as refdimval
   omgtherearesomanykeywordsandstuffthatare40characterslong = "string1"
   thisismakingmyeyesbleed = "string2"
   ...
   exit function return for
end sub function ref dim functionsub

It takes an average of 15 keywords * 5 characters average = 75 characters
to setup the definition of a function (I made that statistic up, but it's
probably close).  Racket uses (define ()) = 11, Haskell uses "=" = 1.  So
the winner is Haskell, at 1/75 the verbosity of basic!  What's worse, is
because you *really* don't want to have to define a new function in basic,
you avoid programming functionally!  So he has all kinds of global
variables to save typing byref dim integer refval functionsub seriouslywtf
end exit just to add 1 to something.  But he gets to drag controls around
on the form, where there's almost no way to explicitly position things in
Racket, and it has to be done with code.

So all 3 of these languages have strikes against them.  I would still vote
in favor of Racket in very many situations.

Lastly, without meaning to be rude, as it's coming from the point of view
of someone who's had similar issues, there's a degree of RTFM present.
 I'll share one other story...in developing a game library for Racket, I
ran into a mystery bug that I eventually realized seemed to be the fault of
Racket and not me.  Despite repeatedly simplifying C code into basically
just pure debug output, it still wasn't doing what it was supposed
to...apparently the linked library wasn't even being loaded at all.  ...And
it wasn't.  But upon scrolling through the FFI documentation, there was
some little line like "btw DrRacket doesn't reload libraries when run is
clicked, you have to restart DrRacket".  So technically it was my fault,
but the documentation could benefit from some kind of "WARNING!" section on
each or at least especially dangerous pages for such pitfalls.  Imagine if
your car explodes if you have the break depressed while turning the AC
dial.  Probably don't want that info on page 87 subsection a.1.c.  But
since there's no way to anticipate all potential user bugs, it's not really
the faul

Re: [racket] Macros baffle me

2014-05-02 Thread Sean Kanaley
Indeed you are correct.  I thought about exactly *why* it's bad to use
datum->syntax, and it can lead to the kind of behavior I have in the below
example:

#lang racket
(define X 100)
(define y 0)
(define-syntax (set-y stx)
  (syntax-case stx ()
[(_ n) #`(set! #,(datum->syntax #'X 'y) n)]))
(let ([y #f])
  (set-y 50)
  y)
y

Will return #f and 50 instead of 50 and 50.  The set-y call inside the let
accidentally used #'X's context (the top level) and so set the y defined
there as (define y 0).  Had it been written as #,(datum->syntax stx 'y),
using the local context where it was called ("stx", from inside of the let
where y is shadowed), it would have set the inner y and the result would be
50 and 0.  Which one is truly correct is up to the macro writer of course,
but since hygienic macros are intended to preserve scope the way lambdas
do, it's probably better to not use datum->syntax where "normal" behavior
is desired.  So Robby's solution is more correct in this sense.  And as the
creators have blogged elsewhere, even when hygiene is seemingly being
broken (anaphoric if), it can still be handled without datum->syntax
through syntax parameters.

Obviously they know everything I just said and more, so I say this as an
addendum to my solution to anyone who might be reading it and get the wrong
idea!  datum->syntax is inherently unsafe!  Does anybody have a simple
example where it's especially helpful/required?


On Fri, May 2, 2014 at 9:37 AM, Robby Findler
wrote:

> I don't think you want to use syntax->datum or datum->syntax in this
> macro. Here's another way to write it.
>
> Robby
>
> #lang racket
> (define-syntax-rule
>   (with-vars (vars ...) x)
>   (for*/and ([vars (in-list '(#t #f))]
>  ...)
> x))
>
> (define-syntax-rule (then x y) (implies x y))
> (define equiv equal?)
>
> (define-for-syntax (collect-fvars stx exp)
>   (let loop ([exp exp])
> (define (collect stx-lst)
>   (apply append (map loop (syntax->list stx-lst
> (syntax-case exp (or then and not)
>   [(or x ...) (collect #'(x ...))]
>   [(and x ...) (collect #'(x ...))]
>   [(then x y) (collect #'(x y))]
>   [(equiv x y) (collect #'(x y))]
>   [(not x) (collect #'(x))]
>   [x
>(identifier? #'x)
>(list #'x)]
>   [_ (raise-syntax-error #f "unknown expression" stx exp)])))
>
> (define-syntax (tauta stx)
>   (syntax-case stx ()
> [(_ exp)
>  #`(with-vars #,(collect-fvars stx #'exp) exp)]))
>
> (tauta (or (then P Q) (then Q (not P
> (tauta (or P (not P))) ; excluded middle
> (tauta (or (and P Q) (or (not P) (not Q))))
> (tauta (equiv (then P Q) (then (not Q) (not P ;equiv
> (tauta (then (and (then (not A) B) (then (not A) (not B))) A))
> ;reductio ad absurdum
> (tauta (equiv (not (and A B)) (or (not A) (not B ; De Morgan's law
>
> On Fri, May 2, 2014 at 8:26 AM, Sean Kanaley  wrote:
> > Here's a solution (at the bottom) with the datum/syntax converters.
>  flatten
> > is built-in, free-vars is basically filtering stuff and then removing
> > duplicates, with-vars can take advantage of the built-in nested for, and
> > then tauta.
> >
> > tauta can get the "quoted" form of the expression like when you used
> eval by
> > calling syntax->datum on the syntax given to tauta, minus "tauta" itself,
> > which is the x pattern.  But the pattern itself is not a syntax object so
> > requires the syntax quote "#'", at which point you can de-syntaxify it
> with
> > syntax->datum, getting '(or (and P Q) etc.).  You can try this in the
> REPL,
> > just do (syntax->datum #'(or (and P Q) etc.)).
> >
> > Once free vars has this as '(P Q), map this list by re-syntaxifying the
> > symbols with datum->syntax.  The first parameter to datum->syntax
> basically
> > is the key to "breaking" hygiene lisp-style.  We want to say that the
> free
> > variable symbols in "x" are the *same* as in our new datum->syntaxified
> > symbols that get passed to with-vars to bind in the for/and, so we say
> they
> > ultimately belong to the same lexical context (your top level code) by
> > passing the same syntax ("stx") that tauta was called in.  In other
> words,
> > those generated vars are created as if you yourself defined them in the
> > module.  Without passing stx to datum->syntax, it would be as if someone
> > else defined them elsewhere but coincidentally with the same names, and
> for
> > safety hygienic systems disallow th

Re: [racket] Macros baffle me

2014-05-02 Thread Sean Kanaley
Here's a solution (at the bottom) with the datum/syntax converters.
flatten is built-in, free-vars is basically filtering stuff and then
removing duplicates, with-vars can take advantage of the built-in nested
for, and then tauta.

tauta can get the "quoted" form of the expression like when you used eval
by calling syntax->datum on the syntax given to tauta, minus "tauta"
itself, which is the x pattern.  But the pattern itself is not a syntax
object so requires the syntax quote "#'", at which point you can
de-syntaxify it with syntax->datum, getting '(or (and P Q) etc.).  You can
try this in the REPL, just do (syntax->datum #'(or (and P Q) etc.)).

Once free vars has this as '(P Q), map this list by re-syntaxifying the
symbols with datum->syntax.  The first parameter to datum->syntax basically
is the key to "breaking" hygiene lisp-style.  We want to say that the free
variable symbols in "x" are the *same* as in our new datum->syntaxified
symbols that get passed to with-vars to bind in the for/and, so we say they
ultimately belong to the same lexical context (your top level code) by
passing the same syntax ("stx") that tauta was called in.  In other words,
those generated vars are created as if you yourself defined them in the
module.  Without passing stx to datum->syntax, it would be as if someone
else defined them elsewhere but coincidentally with the same names, and for
safety hygienic systems disallow this shadowing (their x and your x are
more like x1 and x2, being secretly renamed by the system).  So we tell it
we really mean our own code's context.  In general, you can break hygiene
this way by using whichever syntax object refers to wherever you want to
pretend the syntax came from.

#lang racket
(require (for-syntax racket))

(define-syntax-rule (with-vars (vars ...) x)
  (for*/and ([vars (in-list '(#t #f))]
 ...)
  x))

(define-for-syntax (free-vars xs)
  (define (keyword? x)
(member x '(and or then -> <-> not
equiv display displayln)))
  (remove-duplicates
   (filter (compose not keyword?)
   (flatten xs

(define (then x y) (or y (not x)))
(define (equiv x y) (and (then x y) (then y x)))

(define-syntax (tauta stx)
  (syntax-case stx ()
[(_ x)
 (with-syntax ([(vars ...) (map (λ (var) (datum->syntax stx var))
(free-vars (syntax->datum #'x)))])
   #'(with-vars (vars ...) x))]))

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Optional parameters in Typed Racket?

2014-04-26 Thread Sean Kanaley
According to Sam according to google

http://lists.racket-lang.org/users/archive/2011-November/049010.html

(: append-bar (case-> (String Positive-Integer -> String)
  (String -> String)))
(define (append-bar str [how-many 1])
  (apply string-append str (make-list how-many "bar")))

How come pasting in gmail expands the previous email quote?

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] compile time (file read -> define function)

2014-04-24 Thread Sean Kanaley
Please disregard, this makes no sense.  How would the code refer to
functions that may or may not exist?  I forgot the macro was just
converting a call like (get-function 'name) directly into allowing (name),
so ultimately some sort of lookup is needed.


On Thu, Apr 24, 2014 at 8:17 PM, Sean Kanaley  wrote:

> I have:
>
> 1. a macro to define functions
>
> (define-syntax the-macro
>   ...
>   #'(define (name) ...))
>
> 2. a file filled with "user" definitions in expression form
>
> (this is a definition that shall be passed to the macro)
> (so is this)
> ...
>
> 3. I would like to do something to the effect of
>
> (define-namespace-anchor nsa)
> (with-input-from-file ...
>   (λ ()
> (eval `(the-macro ,@(read))
> (namespace-anchor->namespace nsa
>
> which works, but then I cannot provide the defined functions as they
> happen at phase runtime compile shift meta 34 (?).  Is there some way to
> sort of pre-run the file reading so the definitions already exist for
> exporting?
>

  Racket Users list:
  http://lists.racket-lang.org/users


[racket] compile time (file read -> define function)

2014-04-24 Thread Sean Kanaley
I have:

1. a macro to define functions

(define-syntax the-macro
  ...
  #'(define (name) ...))

2. a file filled with "user" definitions in expression form

(this is a definition that shall be passed to the macro)
(so is this)
...

3. I would like to do something to the effect of

(define-namespace-anchor nsa)
(with-input-from-file ...
  (λ ()
(eval `(the-macro ,@(read))
(namespace-anchor->namespace nsa

which works, but then I cannot provide the defined functions as they happen
at phase runtime compile shift meta 34 (?).  Is there some way to sort of
pre-run the file reading so the definitions already exist for exporting?

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] set!: eval-ing to lvalues

2014-04-23 Thread Sean Kanaley
It appears I have subconsciously plagiarized something I must've read a
long time ago?  Well I'm citing that blog then.


On Wed, Apr 23, 2014 at 5:04 PM, Prabhakar Ragde wrote:

> Stephen Chang wrote:
>
>  Reminds me of this:
>> http://james-iry.blogspot.com/2009/05/brief-incomplete-and-
>> mostly-wrong.html
>>
>> 1990 - A committee formed by Simon Peyton-Jones, Paul Hudak, Philip
>> Wadler, Ashton Kutcher, and People for the Ethical Treatment of
>> Animals creates Haskell, a pure, non-strict, functional language.
>> Haskell gets some resistance due to the complexity of using monads to
>> control side effects. Wadler tries to appease critics by explaining
>> that "a monad is a monoid in the category of endofunctors, what's the
>> problem?"
>>
>
> Philip Wadler retro-legitimized this quote by saying it during a panel
> discussion at the Haskell Symposium 2013 (affiliated with ICFP), which made
> my whole month. --PR
>
> 
>  Racket Users list:
>  http://lists.racket-lang.org/users
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] set!: eval-ing to lvalues

2014-04-23 Thread Sean Kanaley
Unfortunately I forgot which site it was and I deleted my browsing history
as I always do after looking at functional porngramming.


On Wed, Apr 23, 2014 at 9:26 AM, Matthias Felleisen wrote:

>
> On Apr 22, 2014, at 10:10 PM, Sean Kanaley  wrote:
>
> >  a hylomorphism is just an endofunctor in the Hask category of
> profunctorally-dual product monoids with just a hint of commutative free
> applicative comonads and a dash of F-algebra,
>
>
> Do you have citations for that?

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] set!: eval-ing to lvalues

2014-04-22 Thread Sean Kanaley
I'm slightly late to the lens party but Haskell seems to have a solution to
this problem that simultaneously solves another--pattern matching--the
location of a value shouldn't be hard-coded similarly in 50 different
places that deconstruct a struct just to save typing on an accessor, god
forbid the struct change shape or not even be a struct at all anymore.  You
want e.g. current-player-health, not the first of the last of the 3rd
struct pos of the first.

Well with lenses, you can just say

*currentPlayerHealth = _head . 3rdstructpos . _last . _head*

And now you can either set:

*set currentPlayerHealth 4 theState*

or get:

*view currentPlayerHealth theState*

or modify:

*over currentPlayerHealth (+1) theState*

and other stuff.

But these are not macros!  You can thus pass in a lens to determine the
thing you are setting, e.g. in the game of Dominion you might want to move
a card from the player's hand to the table or from the hand to discards, or
from A to B in general.  You can pass in A and B and modify those places
with real functions.

So for Racket, I'm sure everybody who has ever used a mutable struct has
had the desire to pass the field name to modify:

*(struct test (x y) #:mutable #:transparent)*


*(define (over  f a-test)*
*  (set-test-! a-test (f (test- a-test*


*;example usage*

*(let ([t (test 1 2)])*

*  (over y add1 t))*
*=> '(test 1 3)*

Thanks to people smart enough to understand that a hylomorphism is just an
endofunctor in the Hask category of profunctorally-dual product monoids
with just a hint of commutative free applicative comonads and a dash of
F-algebra, this is possible!

I only found one post in the Racket group on lenses, so I am essentially
trying to spread awareness of this, the most powerful thing ever created.
I mean, the type of a lens in Haskell takes 4 parameters.  It has to be
good.


On Sun, Jun 9, 2013 at 6:02 PM, Carl Eastlund  wrote:

> There are a lot of tradeoffs in decisions like this.  Personally, for
> instance, I've never found the desire for a generic set!; I just use a
> specific set! or store a box (mutable reference cell) wherever I need to
> mutate something.  The impact of an lvalue system is going to be different
> for each Scheme that implements it.  And no, the impact would probably not
> be limited to the code that uses mutation.  Features like this usually
> impose a small cost on everything; having two paths through execution means
> that every step that doesn't use an lvalue might still be checking "am I
> using an lvalue now?".  If lvalues mean keeping around references to
> containers longer than they might be needed, it can have a space impact too
> -- the feature might delay garbage collection of the container.
>
> I don't mean to say this feature might not be useful, and it might be very
> interesting research to implement it in an existing Scheme.  I just mean
> it's not immediately obvious that it's a win/win scenario.  Predicting the
> impact of features like this is difficult, because they're interacting with
> so much else in the language.
>
> Carl Eastlund
>
> On Sun, Jun 9, 2013 at 12:28 PM, Sean Kanaley  wrote:
>
>>  Thanks for the explanation.  I suspected it was for efficiency reasons,
>> but as I've never implemented a "real" scheme, I don't know the trade off.
>> I wonder how bad it is.  Way back, they invented lisp.  Then they said it
>> was too slow for real stuff.  Now they say other languages are too weak for
>> real stuff, and lisp's relatively little slowness is made up for by its
>> power.  And here we are, saying a powerful feature would slow it down!
>>
>> Is it 2x, 3x, 4x, 10x, infinityx slower to implement some kind of lvalue
>> system?  And wouldn't that system be necessary only in code that uses the
>> mutation?
>>
>>
>> On 06/09/2013 08:18 AM, Carl Eastlund wrote:
>>
>>  Sean,
>>
>>  Not every Scheme uses an interpreter with an eval function as its
>> primary method of execution, or even at all.  Racket uses a bytecode
>> interpreter and a JIT native-code compiler; the eval function simply
>> triggers compilation to bytecode.  These give a great deal more efficiency
>> than running via eval, and supporting multiple modes of execution would be
>> significantly more expensive.  Evaluating to values by default, rather than
>> to addresses, also gives the compiler a great deal of flexibility.  It
>> doesn't need to keep track of the addresses where it found things and refer
>> to them there in case they are about to be mutated; once they have been
>> "found" via evaluation, they can be copied to register and the original
>> address can be forgotten, if that's most exp

Re: [racket] big-bang is slow to render on screen?

2014-04-21 Thread Sean Kanaley
Here's my log after pasting the source into command-line racket 6.0, Ubuntu
12.04 32-bit:

to-draw at 1649
to-draw: cpu time: 0 real time: 2 gc time: 0
on-key a at 2934
to-draw at 2934
to-draw: cpu time: 0 real time: 2 gc time: 0
on-key s at 2970
to-draw at 2970
to-draw: cpu time: 4 real time: 3 gc time: 0
on-key d at 3044
on-key f at 3044
to-draw at 3045
to-draw: cpu time: 0 real time: 0 gc time: 0
to-draw at 3069
to-draw: cpu time: 0 real time: 1 gc time: 0
on-key a at 3198
on-key s at 3198
to-draw at 3199
to-draw: cpu time: 4 real time: 3 gc time: 0
to-draw at 3329
to-draw: cpu time: 4 real time: 1 gc time: 0
to-draw at 3392
to-draw: cpu time: 0 real time: 1 gc time: 0
on-key g at 3430
on-key j at 3430
on-key k at 3430
to-draw at 3430
to-draw: cpu time: 4 real time: 1 gc time: 0
to-draw at 3467
to-draw: cpu time: 0 real time: 1 gc time: 0
on-key a at 3504
on-key l at 3504
to-draw at 3505
to-draw: cpu time: 0 real time: 1 gc time: 0
to-draw at 3547
to-draw: cpu time: 4 real time: 1 gc time: 0
to-draw at 3572
to-draw: cpu time: 0 real time: 1 gc time: 0
on-key h at 3602
to-draw at 3602
to-draw: cpu time: 0 real time: 1 gc time: 0
on-key k at 3659
on-key ; at 3659
to-draw at 3659
to-draw: cpu time: 4 real time: 3 gc time: 0
to-draw at 3689
to-draw: cpu time: 0 real time: 1 gc time: 0
to-draw at 3725
to-draw: cpu time: 0 real time: 1 gc time: 0
to-draw at 3776
to-draw: cpu time: 0 real time: 1 gc time: 0



On Mon, Apr 21, 2014 at 10:00 AM, Laurent  wrote:

> I have a 2htdp/universe program that used to run fast enough a few months
> ago, but now it is very slow and not usable.
> The slowness seems to be because of the on-screen rendering, and not
> because of the generation of the image.
>
> Here is a stripped-down version that shows this behavior:
> https://gist.github.com/Metaxal/11142941
>
> In the following log, you see that the `on-key` events are very close one
> to the other (in milliseconds after the beginning of the program), but the
> corresponding `to-draw` events are separated by more than a second, even
> though generating the image (cpu time) takes almost no time:
>
> on-key a at 6906
> on-key u at 6912
> on-key i at 6912
> on-key e at 6913
> to-draw at 6913
> to-draw: cpu time: 4 real time: 3 gc time: 0
> to-draw at 8598
> to-draw: cpu time: 4 real time: 2 gc time: 0
> to-draw at 11948
> to-draw: cpu time: 4 real time: 2 gc time: 0
> to-draw at 13631
> to-draw: cpu time: 0 real time: 2 gc time: 0
> to-draw at 161839
> to-draw: cpu time: 4 real time: 9 gc time: 0
>
> During those long seconds, Xorg is almost at 100% cpu.
>
> However, using an empty scene instead of an image is fast.
> The time also depends on the size of the grid.
>
> I'm using Ubuntu 12.04 64bits.
> I have tried to replicate the behavior on older versions of racket (5.3.1
> and 5.90.0.9) but it's the same. So maybe the problem is not on Racket's
> side but something has changed in Ubuntu?
>
> Does anyone else see the same behavior, either on the same platform or on
> a different one?
>
> Thanks,
> Laurent
>
>
> 
>   Racket Users list:
>   http://lists.racket-lang.org/users
>
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] What do first-class structures achieve?

2014-03-13 Thread Sean Kanaley
Printing and transparency are in fact separate:

(struct test (x)
  #:methods gen:custom-write
  [(define (write-proc t p m)
 (write (format "" (test-x t)) p))])

The above untangles the concepts:

> (test 5)
""
> (struct? (test 5))
#f

But I suppose it could be useful to have a comparable default printer
without struct? returning #t, like (struct test (x) #:show)


On Thu, Mar 13, 2014 at 9:00 AM, Matthias Felleisen wrote:

>
> We need to distinguish at least two aspects of this question:
>
> (1) structure instances are first-class values in most languages that
> offer structures.
> Even in the context of C++ you can program as if you were dealing with
> structure
> instances as values.
>
> (2) structure type definitions, such as (struct posn (x y)) are pieces of
> syntax, so
> using the terminology 'first-class' with them is inappropriate. The very
> idea of
> first-class value means something that a program can deal with at run-time
> w/o (m)any restrictions. [You can also define 'first-class' with respect
> to other
> times when programs compute. Even then I have difficulties calling a
> definition
> a first-class object.]
>
> The next part of your question is whether we should have inheritance
> (everything
> is a struct) and whether we should expose it in the teaching languages.
> The former
> is a design decision that I have rarely exploited; my hunch is that a
> programmer
> can live without it and that a meta-/tool-programmer needs it. The latter
> is a
> flaw that we could probably fix easily now.
>
> -- Matthias
>
>
>
>
>
>
>
>
>
> On Mar 13, 2014, at 6:30 AM, Yi D wrote:
>
> Hi,
>
> The documentation says that struct creates structures that are treated as
> first-class
> values. I can see the motivation for pursuing expressiveness. So what do
> we achieve
> using first-class structures? On the down side, I see some problems. For
> example, in
> the Beginning Student language, a posn is both a posn? and a struct?.
>
> > (posn? (make-posn 1 2))
> #t
> > (struct? (make-posn 1 2))
> #t
>
> I guess this is because posn is declared to be #:transparent.
>
> In my opinion, exposing the struct? nature of posn undermines abstraction
> and breaks
> encapsulation. But without declaring it #:transparent, the printer could
> not echo
> informative response. It seems to me the two aspects: exposing the 
> struct?nature and
> informative result are unnecessarily tangled. If they can be separated, we
> may be able
> to give informative result and at the same time not to expose the 
> struct?nature of
> structure types.
>
> Best,
>
> Yi
>  
>  Racket Users list:
>  http://lists.racket-lang.org/users
>
>
>
> 
>   Racket Users list:
>   http://lists.racket-lang.org/users
>
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Knuth's algorithm S

2014-03-10 Thread Sean Kanaley
The current Racket algorithm has an error:

(define counts (build-vector 10 identity))

This sets the counts to their indices, meaning e.g. 9 was pre-counted 9
times.  Switch the first line of the executable portion to run only say 3
trials to see the effects.  It should be:

(define counts (make-vector 10))

Also, multiplying count by (random) should just be (random count):

(when (< (* count (random)) n)
  (vector-set! vec (random n) item

becomes

(when (< (random count) n)
  (vector-set! vec (random n) item




On Mon, Mar 10, 2014 at 2:19 AM, Manfred Lotz  wrote:

> Justfor the records: I updated the version at
>   http://rosettacode.org/wiki/Knuth%27s_algorithm_S#Racket
>
> --
> Manfred
>
>
> 
>   Racket Users list:
>   http://lists.racket-lang.org/users
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] first vs car ; last vs cdr ; empty? vs null?

2014-03-07 Thread Sean Kanaley
Pardon me, but going back a bit where the blog about switching to immutable
lists was mentioned...I saw an interesting comment about immutability and
eq?.  Have any mathematicians come up with an answer for the meaning of eq?
on permanently distinct but equivalent and immutable objects, e.g. (eq?
(cons 3 2) (cons 3 2))?  What about on immutable objects that have mutable
internal state, e.g. memoizing functions?  Naive-but-memoized (fib 1000) is
not necessarily the same as (fib 1000), unless the answer doesn't depend on
the number of universes that have bigbanged meanwhile.



On Fri, Mar 7, 2014 at 2:31 PM, Daniel Carrera  wrote:

> Thanks.
>
>
> On 7 March 2014 20:22, Harry Spier  wrote:
>
>> See also this previous thread on the Racket list.
>>  http://www.mail-archive.com/users%40racket-lang.org/msg12161.html
>>
>>
>>
>>
>> 
>>   Racket Users list:
>>   http://lists.racket-lang.org/users
>>
>>
>
>
> --
> When an engineer says that something can't be done, it's a code phrase
> that means it's not fun to do.
>
> 
>   Racket Users list:
>   http://lists.racket-lang.org/users
>
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Using big-bang with picts

2014-02-17 Thread Sean Kanaley
(define (world->image w)
  (overlay (pict->bitmap (circle w))
   (empty-scene 100 100)))


On Mon, Feb 17, 2014 at 1:40 PM, Jens Axel Søgaard wrote:

> Hi All,
>
> Is there a way to use big-bang with picts?
> In other words, how can I convert a pict into something that big-bang
> will display?
>
> The attempt below fails with this error:
>
> collects/racket/private/class-internal.rkt:4387:0: send: no such method
> method name: copy
> class name: bitmap%
>
> #lang racket
> (require pict (only-in 2htdp/universe big-bang on-tick to-draw))
>
> (define (world->image w)
>   (pict->bitmap (circle w)))
>
> (big-bang 100
>   [on-tick add1]
>   [to-draw world->image])
>
>
> --
> Jens Axel Søgaard
>
> 
>   Racket Users list:
>   http://lists.racket-lang.org/users
>

  Racket Users list:
  http://lists.racket-lang.org/users


[racket] Rosetta Task: RCRPG

2014-02-07 Thread Sean Kanaley
https://github.com/Seanner/RCRPG/blob/master/mud.rkt

It's pretty minimal (polished only to not crash on bad user input) so if
anybody wants to mess with it before I upload it, please feel free.  There
are a few things that are seemingly illogical like using one-shot macros
that take up more code than they save, but since it's for Rosetta there was
more incentive to use fancy stuff.

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] FYI: A new Racket-powered startup

2014-02-05 Thread Sean Kanaley
On-topic, congratulations on using a superior language in the real world.

On-latest-topic, maybe indoctrination is the answer:

I pledge allegiance...to functional programming
And the open source coders of America
And to the recursion...for which it stands
One function, under lambda, immutable
With purity and conciseness for all

It brings a tear to my eye.

  Racket Users list:
  http://lists.racket-lang.org/users


[racket] Nested macros to refer to user's lexical context?

2014-01-24 Thread Sean Kanaley
A macro like

(define-syntax (mac stx)
  (... generate user scope function by passing stx to format-id ...))

doesn't work (function is unbound in phase 0) if I use optional parameters
and telescoping cases:

(syntax-case ...
  [(_ param ...) #'(mac some-default-thing param ...)]
  [(_ optional-thing param ...) #'the-main-expansion]

This is presumably because the second call to "mac" is now in a different
context.  The solution I have is to thread stx through recursive calls:

(define-syntax (mac stx)
  (define (aux original-stx stx)
( ... cases here and pass original-stx to format-id ... )
  (syntax-case stx ()
[(orig rest ...) (aux #'orig #'(rest ...))]))

I was hoping there was something that stores the context of the original
macro call for just this kind of thing, so it could be written like the
first version but with permanent access to its original call's context
through nested expansion code, or perhaps I'm going about it wrong.  Also,
in the above example, orig != stx in the sense that passing stx to
format-id results in the undefined in phase 0 error:

(define-syntax (mac stx)
  (define (aux aux-stx)
(... cases here and pass stx to format-id ...)
  (aux stx))

What makes that fail?

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Style. for/fold for/list for/lists

2014-01-22 Thread Sean Kanaley
Replying to the entire list is hard to remember...

This doesn't have the full fanciness of the for--- series, but perhaps this
is a useful starting point along your suggested API?

(define (make-collector init-val mappend)
  (let ([v init-val])
(λ args
  (case (length args)
[(0) v]
[(1) (set! v (mappend (car args) v))]
[else (error "for/collect: blah blah blah")]

(define-syntax collector
  (syntax-rules (list sum)
[(_ sum) (make-collector 0 +)]
[(_ list) (make-collector '() cons)]
;etc.
))

(define-syntax-rule (for/collect ([acc type] ...) ([i lst] ...) body ...)
  (let ([acc (collector type)] ...)
(let loop ([i lst] ...)
  (cond [(or (null? i) ...) (values (acc) ...)]
[else (let ([i (car i)] ...)
body ...)
  (loop (cdr i) ...)]

It does use set!, as you feared, but since it's entirely local to the
collector implementation I don't think it counts as breaking purity.


On Wed, Jan 22, 2014 at 6:49 PM, Sean Kanaley  wrote:

> This doesn't have the full fanciness of the for--- series, but perhaps
> this is a useful starting point along your suggested API?
>
> (define (make-collector init-val mappend)
>   (let ([v init-val])
> (λ args
>   (case (length args)
> [(0) v]
> [(1) (set! v (mappend (car args) v))]
> [else (error "for/collect: blah blah blah")]
>
> (define-syntax collector
>   (syntax-rules (list sum)
> [(_ sum) (make-collector 0 +)]
> [(_ list) (make-collector '() cons)]
> ;etc.
> ))
>
> (define-syntax-rule (for/collect ([acc type] ...) ([i lst] ...) body ...)
>   (let ([acc (collector type)] ...)
> (let loop ([i lst] ...)
>   (cond [(or (null? i) ...) (values (acc) ...)]
> [else (let ([i (car i)] ...)
> body ...)
>   (loop (cdr i) ...)]
>
> It does use set!, as you feared, but since it's entirely local to the
> collector implementation I don't think it counts as breaking purity.
>

  Racket Users list:
  http://lists.racket-lang.org/users


[racket] Possible bug with "const"?

2014-01-10 Thread Sean Kanaley
> (define x (build-vector 4 (const (vector 1

> (vector-set! (vector-ref x 2) 0 5)

> x
'#(#(5) #(5) #(5) #(5))

 vs. --

> (define x (build-vector 4 (λ (x) (vector 1

> (vector-set! (vector-ref x 2) 0 5)

> x
'#(#(1) #(1) #(5) #(1))

---

Maybe I'm misunderstanding const, but to me it means "ignore arguments" as
opposed to signifying shared-structure / immutability (like a "constant").
That's what #(1) is for.  The top version should I believe constantly
return a fresh (different) vector regardless of its arguments.

I'm on 5.3.4 due to Ubuntu, in case this was already found.

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Something to achieve "define-syntax-parameter-for-syntax" or "set!-for-syntax"?

2014-01-05 Thread Sean Kanaley
*cough* my test cases at the moment amount to pressing the keys and seeing
that the appropriate actions are being taken.  I suppose I will need to
write official tests.


On Sun, Jan 5, 2014 at 1:32 PM, Matthias Felleisen wrote:

>
> It is an unusual way to break syntax but I can't think of a serious
> drawback off the top of my head. (I am sure Ryan and Matthew can think of
> one.) Does it pass your test cases?
>
>
> On Jan 5, 2014, at 1:21 PM, Sean Kanaley wrote:
>
> > Ha!  The below solution is a macro-making macro that re-syntaxifies
> "params ..." to "belong to" the inner macro:
> >
> > (define-syntax-rule (make-commands name params ...)
> >   (define-syntax (name inner-stx)
> > (syntax-case inner-stx ()
> >   [(_ (c f) (... ...))
> >(with-syntax ([(ps (... ...)) (datum->syntax inner-stx
> (syntax->datum #'(params ...)))])
> >  #'(list (cons (symbol->string 'c)
> >(λ (ps (... ...)) f))
> >  (... ...)))])))
> >
> > I'm not sure if this is the canonical solution, but nevertheless I think
> it's pretty awesome that this is possible and seems to work.
> > 
> >  Racket Users list:
> >  http://lists.racket-lang.org/users
>
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Something to achieve "define-syntax-parameter-for-syntax" or "set!-for-syntax"?

2014-01-05 Thread Sean Kanaley
Ha!  The below solution is a macro-making macro that re-syntaxifies "params
..." to "belong to" the inner macro:

(define-syntax-rule (make-commands name params ...)
  (define-syntax (name inner-stx)
(syntax-case inner-stx ()
  [(_ (c f) (... ...))
   (with-syntax ([(ps (... ...)) (datum->syntax inner-stx
(syntax->datum #'(params ...)))])
 #'(list (cons (symbol->string 'c)
   (λ (ps (... ...)) f))
 (... ...)))])))

I'm not sure if this is the canonical solution, but nevertheless I think
it's pretty awesome that this is possible and seems to work.

  Racket Users list:
  http://lists.racket-lang.org/users


[racket] Something to achieve "define-syntax-parameter-for-syntax" or "set!-for-syntax"?

2014-01-05 Thread Sean Kanaley
Hello,

First the short question: is there a way that user code can set some sort
of in-effect global variable to determine how a library macro will expand?
The problem I have is there doesn't seem to be a way to combine the
concepts of parameters/globals and transformer environments.

Long part in case it's not clear why I'm trying to do this or if someone
knows a better way (I was hoping writing this would cause me to figure it
out and avoid having to ask the question, as is usually the case.  It did
not work.):

I am attempting to define a library macro.  This macro's expansion should
be based on the user's global parameterization of it.  It is a macro to
create an association list between "commands" and functions for keyboard
input (or any input).  The association list looks like this for example:

'([left (lambda (params ...) (code-to-move-left))]
  [right (lambda (params ...) (code-to-move-right))])

where there is some config file like:

a = left
d = right

that associates keys to commands, and ultimately the library associates
keys to code by combining the two associations transitively.

The macro named "commands" to build the first table is written to save on
the duplicate "(lambda (param ...)" portion, so the user code building the
alist goes like this:

(commands (params ...)
  (left (code-to-move-left))
  (right (code-to-move-right)))

The problem comes in when the user does not define commands all at once.
Two calls to the "commands" macro require using the same parameter list,
since there is a top-level "run-input" function that checks if a key is
down and runs the associated function, passing in the generic parameter set
(regardless of which / if any keys that are down).  So I want to have
"commands" be defined something like this:

(define-syntax (commands stx)
  (syntax-case stx ()
[(_ (c f) ...)
 #`(list (cons (symbol->string 'c)
   (λ #,input-params f))
 ...)]))

Where input-params is bound to the syntax of the parameter list.  The usage
is ideally:

(define users-constant #'(state delta-time))

(syntax-paramterize or set! or whatever on input-params to users-constant
  (commands
(left (move-left! state (* speed delta-time)))
(right (move-right! etc...

expanding into:

'([left (lambda (state delta-time) (move-left! state (* speed delta-time)))]
  [right etc...])

But I can't figure it out.

By placing this hypothetical extension of the library code into the user
code, I can write this as a wrapper macro on "commands" that shares the
user's constant piece of syntax using datum->syntax:

(define-for-syntax (input-params stx)
  (datum->syntax stx '(state delta-time)))

(define-syntax (cmds stx)
  (syntax-case stx ()
[(_ body ...)
 #`(commands #,(input-params stx)
   body ...)]))

and now all calls to cmds will share a single parameter list as required.
But this is weak because this code will be the same for every user except
the actual parameter list embedded within input-params definition, so I'm
looking for a way to get the above functionality into the library, yet
still have the user define the "'(state delta-time)" portion themselves.
Basically copy paste the "cmds" definition into the library, and then I
would just need "set!-for-syntax input-params '(state delta-time)" to be
possible.

One day I hope to have a Racket + OpenGL answer to something like XNA.
That day is not today.

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Roadmap for Racket

2013-07-17 Thread Sean Kanaley
Rocket


On Wed, Jul 17, 2013 at 12:52 PM, Joe Gilray  wrote:

> Racket2 name suggestion:
>
> (add1 racket)
>
> :-)
>
> -Joe
>
>
> On Wed, Jul 17, 2013 at 7:29 AM, John Griffin  wrote:
>
>> I meant "LATER when it arrives", not "LATE when it arrives."
>>
>> Thanks again,
>> -JG
>>
>>  On Jul 17, 2013, at 9:56 AM, John Griffin  wrote:
>>
>> Matthew, Robby, Jay, Sam, and Matthias,
>>
>> Thanks very much for the thoughtful response.  Having a new racket2
>> language and smaller runtimes will be welcome improvements on the technical
>> front.   I look forward to a settling on a stable 5.3.6 for current code as
>> well as seeing version 6 late when it arrives.
>>
>>  -John Griffin
>>
>>
>>
>>
>>
>> 
>>   Racket Users list:
>>   http://lists.racket-lang.org/users
>>
>>
>
> 
>   Racket Users list:
>   http://lists.racket-lang.org/users
>
>

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Eval / Lazy Macros followup

2013-07-05 Thread Sean Kanaley

On 07/05/2013 07:33 PM, Eli Barzilay wrote:
I'm not sure that I followed things correctly, but the problem with 
`mappend' is that it's yet another piece of fuunctionality that needs 
to be defined in the lazy language to ensure that it's not too strict. 
If you're just requiring it from `racket/list' ... 


I believe you mean append-map? I mean the monoidal dot/multiply/times, 
called mappend by Haskell. It does though require lazy arguments and 
I've switched everything to #lazy but I seem to be running into problems 
with macros generating proper code, despite them working just fine in 
strict Racket, except for the improper strictness. The main problem is 
I'm left with a promise instead of a value when e.g. using REPL to call 
one of the generated functions. It's possibly related to the expansion 
code using strict begin instead of lazy begin, but lazy begin gave 
errors preventing the macros from even being generated at all, claiming 
define-syntax cannot be used within it (expression not allowed in 
context or something like that).


I don't have github or anything like that, so I apologize in advance for 
pasting here (80 lines total) but I suppose one can just paste it into 
DrRacket. It's not so complex aside from the define-type-class syntax 
portion, but reading anything at all is not required. I like to work on 
many projects in parallel to keep from getting bored, so... But, if 
interested, the *only* changes from the working code (aside from being 
buggy with respect to and/or) is switching to #lazy and the required 
racket/base import to have phase1 stuff.


#lang lazy
(require (for-syntax racket/syntax
(rename-in racket/base (begin !begin)))
(rename-in racket/base (begin !begin)))

(provide
define-type-class
instance-type-class
instance-type-class/sub
using
use-sub
!begin)

(define methods (make-hash))

(define (put! name instance f)
(hash-set! methods (cons name instance) f))

(define (put-default! name f)
(hash-set! methods name f))

(define (get name instance)
(hash-ref methods (cons name instance) (λ () (get-default name

(define (get-default name)
(hash-ref methods name (λ () (error "method not defined" name

(define (apply-generic name instance . args)
(apply (get name instance) args))

(define-syntax-rule (define-generic (name type-class arg ...))
(define (name arg ...)
(apply-generic 'name (car (type-class)) arg ...)))

(define-syntax-rule (define-default-method (name arg ...) body ...)
(put-default! 'name (λ (arg ...) body ...)))

(define-syntax-rule (define-method (name instance arg ...) body ...)
(put! 'name 'instance (λ (arg ...) body ...)))

(define-syntax (define-type-class stx)
(define (parse-def name d)
(syntax-case d ()
[(generic (arg ...) body ...)
#`(!begin
#,(parse-def name #`(generic arg ...))
(define-default-method (generic arg ...) body ...))]
[(generic arg ...)
#`(define-generic (generic #,name arg ...))]))
(syntax-case stx ()
[(_ name generic-def ...)
(with-syntax ([def-name (format-id stx "define/~a" #'name)])
#`(!begin
(define name (make-parameter #f))
(define-syntax-rule (def-name instance (f a (... ...)) body (... ...))
(define (f a (... ...))
(using ([name instance])
body (... ...
#,@(map (λ (d) (parse-def #'name d))
(syntax->list #'(generic-def ...)]))

(define-syntax-rule (instance-type-class class-name instance (method 
(arg ...) body ...) ...)

(!begin
(define-method (method instance arg ...)
body ...)
...))

(define-syntax-rule (using ([type-class instance ...] ...) body ...)
(parameterize ([type-class '(instance ...)] ...)
body ...))

(define-syntax-rule (use-sub type-class body ...)
(parameterize ([type-class (cdr (type-class))])
body ...))

(define-syntax-rule (instance-type-class/sub class-name instance (method 
(arg ...) body ...) ...)

(!begin
(define-method (method instance arg ...)
(use-sub class-name body ...))
...))

If any one is still here, here is the monoid module that doesn't work so 
hot with #lazy:


#lang lazy
(require "core.rkt")

(provide (all-defined-out))

(define-type-class monoid
(mempty)
(mappend a b))

(define (mappend* . ms) (foldr mappend (mempty) ms))

(instance-type-class monoid list
(mempty () '())
(mappend (a b) (append a b)))

(instance-type-class/sub monoid result
(mempty () (mempty))
(mappend (a b) (λ (x) (mappend (a x) (b x)

(instance-type-class monoid void
(mempty () (void))
(mappend (a b) (void)))

(instance-type-class/sub monoid cons
(mempty () (cons (mempty) (mempty)))
(mappend (a b) (cons (mappend (car a) (car b))
(mappend (cdr a) (cdr b)

(instance-type-class/sub monoid dual
(mempty () (mempty))
(mappend (a b) (mappend b a)))

(instance-type-class monoid endo
(mempty () identity)
(mappend (a b) (compose a b)))

(instance-type-class monoid all
(mempty () #t)
(mappend (a b) (and a b)))

(instance-type-class monoid any
(mempty () #f)
(mappend (a b) (or a b)))

(instance-type-class monoid sum
(mempty () 0)
(mappend (a b) (+ a b)))

(instance-type-class monoid product
(mempty () 1)
(mappend (a

Re: [racket] Offtopic: Favorite resources for mastering SML?

2013-07-04 Thread Sean Kanaley
I can't speak to ML vs. Haskell starter-friendliness but I can provide a 
link to a free online Haskell book:


http://book.realworldhaskell.org/read/

It's the Haskell equivalent of "Practical Common Lisp".

If you end up liking Haskell, the book Haskell School of Expression is 
very good.  It takes you through the construction of DSLs for functional 
reactive programming (FRP), an imperative language to control robots 
(simulated on screen with simple graphics), and one to describe music in 
the abstract and then convert it to a MIDI file.  It's more heavily math 
based, often asking for proofs as exercises, but if that's not what you 
like it's not really necessary to do them anyway.


Note that I'm not attempting to persuade you from ML and the 
recommendations already given, merely sharing what I personally know 
better...though I will say that the Haskell type system to include its 
classes, families, functional dependencies, transformers, GADTs, etc. is 
probably the best one in existence, or at least in common use...


On 07/04/2013 10:36 AM, Grant Rettke wrote:

Hi,

One of my current projects is to master as functional and statically
typed programming language. Having discussed and debated it years ago
(partially on list here, too) the conclusion was reached that SML
would be a nicer place to start than Haskell or Clean. Fifteen years
after its release, there seems to be a lot of knowledge but not a ton
of resources exactly. There are a lot of dead links and books out of
print (working off the SML/NJ resource list). I'm wondering of ACM's
digital library is a good place to start.

Last week I worked through _ML for the Working Programmers_ which was
great but didn't get into the details in a way that I would have
expected (went from 10mph to 100mph instead). Up next is _The Little
MLer_ and Harpers _Programming in Standard ML_.

This list's members have a breadth and depth far beyond most, so I'm
wondering if I could get your help here and learn about your favorite
learning SML resources.

Best wishes,




 Racket Users list:
 http://lists.racket-lang.org/users


Re: [racket] How to either extend eval or write macros in #lazy?

2013-07-02 Thread Sean Kanaley
Yes, but first I'll say the issue is with a nested define-syntax inside 
of a lazy begin (a macro-writing macro). I got it to sort of work by 
renaming racket/base begin to !begin and using that instead, but then 
the resulting usage of the functions in "user code" does not evaluate 
the promises that #lazy creates and require being wrapped by (! ...). 
Here is the macro-writing-macro:


(define-syntax (define-type-class stx)

(define (parse-def name d)
(syntax-case d ()
[(generic (arg ...) body ...)
#`(!begin
#,(parse-def name #`(generic arg ...))
(define-default-method (generic arg ...) body ...))]
[(generic arg ...)
#`(define-generic (generic #,name arg ...))]))

(syntax-case stx ()
[(_ name generic-def ...)
(with-syntax ([def-name (format-id stx "define/~a" #'name)])
#`(!begin

(define name (make-parameter #f))

(define-syntax-rule (def-name instance (f a (... ...)) body (... ...))

(define (f a (... ...))
(using ([name instance])
body (... ...

#,@(map (λ (d) (parse-def #'name d))
(syntax->list #'(generic-def ...)]))

Roughly what it does is define generic methods that may have a default 
implementation provided just like in Haskell, as well as, in the 
"def-name" output, generate a macro to define functions that 
automatically parameterize the active class instance for a given type 
class (I did this to avoid dispatching on argument types since "mempty" 
takes no arguments. It seemed necessary to provide type information 
manually outside of the method calls.)


One potential band aid solution is to wrap the thing that applies generics:

(define-syntax-rule (define-generic (name type-class arg ...))
(define (name arg ...)
(apply-generic 'name (car (type-class)) arg ...)))

with a "!", so it'd be (! (apply-generic ...) ...)

But I'm not sure this is the proper solution or perhaps my definitions 
are somehow incorrect altogether.


On 07/01/2013 05:19 PM, Stephen Chang wrote:

For #2, can you give a more specific example?

For example, I can do this:

#lang lazy
(require (for-syntax racket/base))

(cons 1 (cons 2 (cons 3 null)))

(define-syntax econs
   (syntax-rules () [(_ x y) (cons x (! y))]))

(econs 1 (econs 2 (econs 3 null)))


Welcome to DrRacket, version 5.3.4.11 [3m].
Language: lazy; memory limit: 8192 MB.
'(1 . #)
'(1 2 3)
On Mon, Jul 1, 2013 at 2:31 PM, Sean Kanaley  wrote:

I'm attempting to provide a package very soon with Haskell-like type classes
initially including Monoid, Functor, and Foldable, however I've discovered
the terrible bug that mappend is too strict when it expands into "or" or
"and".

Is there a way to extend eval from within #lang racket such that the user
can still use #lang racket while I secretly have an extended version?  I
would then add a lazy-lambda construct without requiring the entire set of
future racket programs written using this library to be lazy.  In other
words, if eval was a superclass or interface available in #lang racket,
someone calling (mappend ...) would get the closure of some sort to be
applied by this generic eval that I would implement internally to handle the
fact that it's not a regular lambda.  If not, then solution 2:

#lazy ... simply using #lazy causes a couple issues:

1. define is not defined at phase1, solved by (require (for-syntax
racket/base) ...)

2. define-syntax not valid in expression context etc. ... not sure how to
solve ... it looks like #lazy doesn't permit internal definitions, but then
how does one make a macro in lazy racket?

  Racket Users list:
  http://lists.racket-lang.org/users





 Racket Users list:
 http://lists.racket-lang.org/users


[racket] Eval / Lazy Macros followup

2013-07-01 Thread Sean Kanaley

Please disregard the first option as it would be semantically incorrect...

One could then not use mappend as a higher order function properly as 
the arguments would've been evaluated already in, say, the list if 
mappend is folded in.


So I'll have to use lazy, but how does one write macros with it?

 Racket Users list:
 http://lists.racket-lang.org/users


[racket] How to either extend eval or write macros in #lazy?

2013-07-01 Thread Sean Kanaley
I'm attempting to provide a package very soon with Haskell-like type 
classes initially including Monoid, Functor, and Foldable, however I've 
discovered the terrible bug that mappend is too strict when it expands 
into "or" or "and".


Is there a way to extend eval from within #lang racket such that the 
user can still use #lang racket while I secretly have an extended 
version?  I would then add a lazy-lambda construct without requiring the 
entire set of future racket programs written using this library to be 
lazy.  In other words, if eval was a superclass or interface available 
in #lang racket, someone calling (mappend ...) would get the closure of 
some sort to be applied by this generic eval that I would implement 
internally to handle the fact that it's not a regular lambda.  If not, 
then solution 2:


#lazy ... simply using #lazy causes a couple issues:

1. define is not defined at phase1, solved by (require (for-syntax 
racket/base) ...)


2. define-syntax not valid in expression context etc. ... not sure how 
to solve ... it looks like #lazy doesn't permit internal definitions, 
but then how does one make a macro in lazy racket?


 Racket Users list:
 http://lists.racket-lang.org/users


Re: [racket] REPL @ Runtime Contract Modification?

2013-06-27 Thread Sean Kanaley

Thanks, that's what I wanted.

But unfortunately it doesn't work as the function apparently was 
compiled inline or something to that effect.


As a more general solution to this kind of interactive debugging issue, 
how difficult would implementing a typical Common Lisp REPL be?  I'm 
thinking of adding the kind of error/condition handler like:


"

enter a number:

0 - enter new value
1 - exit to top level
2 - exit one level
3 - print stack trace
4 - etc.

I'm not familiar with Racket's internals so I don't know how much this 
is a REPL hack vs. rewriting the whole system (the condition system 
isn't necessary)...  If it's not too impossible I would be happy to make 
this contribution...


On 06/27/2013 12:14 PM, Matthias Felleisen wrote:

Got it.

Assuming f is assignable:
-- define a new version of the function with its improved contract
   (define/contract fprime ...)
-- (set! f fprime)





On Jun 27, 2013, at 10:53 AM, Sean Kanaley  wrote:


All of Racket seems to be available while debugging GUIs.  I can query state 
and launch new error-free dialogs while the GUI sits there with its broken 
dialog.  I was thinking then that there might be some way to change the 
associated contract of the offending function while the GUI patiently waits for 
its next event.

Also it was type [A]...I made the mistake of calling the range of a function like 
"member" "boolean?".

The goal is to enter:

(set-contract!  (-> ... (listof symbol?))

and carry on.

On 06/27/2013 10:32 AM, Matthias Felleisen wrote:

I am not sure what you're asking.

-- Once your program has raised a contract error and your program didn't handle 
it, you're stuck.

-- Did the contract error suggest

  [A] you formulated the wrong contract (the program is working but the 
contract is too stringent)
  [B] you program has a bug

Before you restart try to figure out which one is which and fix something.




On Jun 27, 2013, at 12:35 AM, Sean Kanaley  wrote:


Hello,

I'm debugging a heavily stateful GUI app that has reached a very specific state 
but has come across a contract error.  Is there some way to modify the contract 
and proceed or I must I reevaluate and run the gui and attempt to duplicate the 
state?

Racket Users list:
http://lists.racket-lang.org/users



 Racket Users list:
 http://lists.racket-lang.org/users


Re: [racket] REPL @ Runtime Contract Modification?

2013-06-27 Thread Sean Kanaley
All of Racket seems to be available while debugging GUIs.  I can query 
state and launch new error-free dialogs while the GUI sits there with 
its broken dialog.  I was thinking then that there might be some way to 
change the associated contract of the offending function while the GUI 
patiently waits for its next event.


Also it was type [A]...I made the mistake of calling the range of a 
function like "member" "boolean?".


The goal is to enter:

(set-contract!  (-> ... (listof symbol?))

and carry on.

On 06/27/2013 10:32 AM, Matthias Felleisen wrote:

I am not sure what you're asking.

-- Once your program has raised a contract error and your program didn't handle 
it, you're stuck.

-- Did the contract error suggest

  [A] you formulated the wrong contract (the program is working but the 
contract is too stringent)
  [B] you program has a bug

Before you restart try to figure out which one is which and fix something.




On Jun 27, 2013, at 12:35 AM, Sean Kanaley  wrote:


Hello,

I'm debugging a heavily stateful GUI app that has reached a very specific state 
but has come across a contract error.  Is there some way to modify the contract 
and proceed or I must I reevaluate and run the gui and attempt to duplicate the 
state?

Racket Users list:
http://lists.racket-lang.org/users



 Racket Users list:
 http://lists.racket-lang.org/users


[racket] REPL @ Runtime Contract Modification?

2013-06-26 Thread Sean Kanaley

Hello,

I'm debugging a heavily stateful GUI app that has reached a very 
specific state but has come across a contract error.  Is there some way 
to modify the contract and proceed or I must I reevaluate and run the 
gui and attempt to duplicate the state?


 Racket Users list:
 http://lists.racket-lang.org/users


[racket] Realm of Racket as Starting Book?

2013-06-25 Thread Sean Kanaley

To the authors:

I have recommended Realm of Racket to a friend who expressed an interest 
in programming in conjunction with HtDP.  Now, I'm sure the creators 
would "strongly encourage" future software engineers to be comfortable 
with the material in HtDP, but exactly how difficult is the "intended 
for novices with basic exposure to programming" Realm of Racket?  I ask 
because I'd rather not give him two books to work through at the same 
time and have him lose interest trying to solve n-queens and implement 
BFS vs making (to him possibly more interesting) games.


I'm geographically close in real life to I can also lend assistance in 
the beginning.  So is it a true starter book?


 Racket Users list:
 http://lists.racket-lang.org/users


Re: [racket] Definition of DSL?

2013-06-24 Thread Sean Kanaley
As said in SICP, "eval" is the ultimate language interpreter, capable of 
implementing anything computable.  You could feed it code (a language) 
to interpret C code (the DSL to interpret C, so this code in turn takes 
a parameter of the C to interpret just as eval takes a parameter of the 
Scheme to interpret).  Now in effect, by running (eval (eval-c 
)), eval interprets C! But does the thing fed to eval 
have to be an eval-er of a pre-existing "main language" to qualify as an 
interpreter for a DSL?  How complex must the input to the 
sub-interpreter be to breach into DSL territory?  I believe there is no 
minimum, and therefore every function is part of some DSL:


(define (eval-q l)
  (for-each displayln l))

The Q language, unlike C, is very simple.  The grammar is any Scheme 
list, which it interprets by printing elements into newlines. "eval-q" 
makes "eval" now instead eval Q:


> (eval '(list 1 2 3))
'(1 2 3)

> (eval '(eval-q (list 1 2 3)))
1
2
3

The fact that eval-q falls short of implementing C to me does not make 
it a non-DSL.  Its domain just happens to be limited to printing 
elements of a list.  In other words, why are the following different:


(eval '(eval-q '(1 2 3)))

(eval '(eval-c "int main() { return 0; }"))

If the answer is that eval-c must have a more difficult implementation, 
I don't believe that's the essence of a DSL!


An example of a more powerful DSL though that similarly does not rely on 
macros or requiring different input syntax is the picture language from 
SICP, or any of the languages from the Haskell School of Expression.


The best way to program is to solve the problem in a language perfect 
for solving the problem.  Otherwise, the program is written 
inefficiently relative to this better language.  To this end, every new 
definition (abstraction) must either bolster the language towards 
solving the problem directly, or, once at this level, solve the problem 
directly.  Every abstraction defined that is not an immediate "solution 
node" can then be considered part of DSL for that solution.


 Racket Users list:
 http://lists.racket-lang.org/users


Re: [racket] Modules and File Save Bug?

2013-06-22 Thread Sean Kanaley
Yes but then my question is, is the defined behavior to display tests 
that are being run in a different tab in the current tab's repl?  I 
understand this kind of behavior when file A imports B and B's last 
expression is say 3, then running A will print 3 in A's repl if the 
require is the only expression in A, but this potential bug is the other 
way around.  Why would B importing A display things in *A's* window when 
running A?


On 06/22/2013 03:40 PM, Robby Findler wrote:
The requires depend on what is in the filesystem, not what is in the 
editor. Does that explain what you are seeing, perhaps?


Robby


On Sat, Jun 22, 2013 at 2:38 PM, Sean Kanaley <mailto:skana...@gmail.com>> wrote:


I've got it this time:

The test file with the module+ must be required by another, not
even necessarily saved file (untitled # is fine).  It seems the
tests are being run therefore in the *other* file, yet displayed
in the current file's repl.

e.g.

in a.rkt:

#lang racket

(module+ test
  (write "?"))

save, then open new tab

#lang racket
(require "a.rkt")

go back to a.rkt, comment out, and it will print.  It may or may
not print after depending on exactly which order of
save/ctrl+r/commenting/etc. and I'm not sure what happens in general.


On 06/22/2013 03:30 PM, Robby Findler wrote:

Oh, maybe memory got corrupted somehow earlier along the line.

Just in case it is relevant: DrRacket tries hard to protect
itself against buggy user programs, but it cannot do that when
#%foreign is being used (unsafely).

Robby



On Sat, Jun 22, 2013 at 2:25 PM, Sean Kanaley mailto:skana...@gmail.com>> wrote:

I myself can no longer reproduce it after closing and
reopening DrRacket.  By coincidence, before closing it, the
menus stopped working and I got a Ubuntu error of some sort
as well.  I shall keep trying for a bit.


On 06/22/2013 03:12 PM, Robby Findler wrote:

I'm not seeing that behavior (that is a bug, tho). I tried
these steps:

1) cmd-t to create a new tab in DrRacket.
2) paste the expression above (there is an automatic "#lang
racket" inserted).
3) save the file.
4) delete the above expression
5) hit run.

No output observed.

Were you doing something differently?

Robby


On Sat, Jun 22, 2013 at 2:02 PM, Sean Kanaley
mailto:skana...@gmail.com>> wrote:

I don't use modules very much, so this could be the
defined behavior similar to how the ffi module
"secretly" (it's actually documented) doesn't reload
foreign libraries unless DrRacket is restarted, but I
didn't notice anything in the documentation.  How to
reproduce:

(module+ test
  (write "?"))

Without even running it, save the file, then delete that
expression.  Now run it (as in ctrl+r), and it will
write "?".

 Racket Users list:
http://lists.racket-lang.org/users











  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Modules and File Save Bug?

2013-06-22 Thread Sean Kanaley

I've got it this time:

The test file with the module+ must be required by another, not even 
necessarily saved file (untitled # is fine).  It seems the tests are 
being run therefore in the *other* file, yet displayed in the current 
file's repl.


e.g.

in a.rkt:

#lang racket
(module+ test
  (write "?"))

save, then open new tab

#lang racket
(require "a.rkt")

go back to a.rkt, comment out, and it will print.  It may or may not 
print after depending on exactly which order of 
save/ctrl+r/commenting/etc. and I'm not sure what happens in general.


On 06/22/2013 03:30 PM, Robby Findler wrote:

Oh, maybe memory got corrupted somehow earlier along the line.

Just in case it is relevant: DrRacket tries hard to protect itself 
against buggy user programs, but it cannot do that when #%foreign is 
being used (unsafely).


Robby



On Sat, Jun 22, 2013 at 2:25 PM, Sean Kanaley <mailto:skana...@gmail.com>> wrote:


I myself can no longer reproduce it after closing and reopening
DrRacket. By coincidence, before closing it, the menus stopped
working and I got a Ubuntu error of some sort as well.  I shall
keep trying for a bit.


On 06/22/2013 03:12 PM, Robby Findler wrote:

I'm not seeing that behavior (that is a bug, tho). I tried these
steps:

1) cmd-t to create a new tab in DrRacket.
2) paste the expression above (there is an automatic "#lang
racket" inserted).
3) save the file.
4) delete the above expression
5) hit run.

No output observed.

Were you doing something differently?

    Robby


On Sat, Jun 22, 2013 at 2:02 PM, Sean Kanaley mailto:skana...@gmail.com>> wrote:

I don't use modules very much, so this could be the defined
behavior similar to how the ffi module "secretly" (it's
actually documented) doesn't reload foreign libraries unless
DrRacket is restarted, but I didn't notice anything in the
documentation.  How to reproduce:

(module+ test
  (write "?"))

Without even running it, save the file, then delete that
expression.  Now run it (as in ctrl+r), and it will write "?".

 Racket Users list:
http://lists.racket-lang.org/users








  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Modules and File Save Bug?

2013-06-22 Thread Sean Kanaley
I myself can no longer reproduce it after closing and reopening 
DrRacket.  By coincidence, before closing it, the menus stopped working 
and I got a Ubuntu error of some sort as well.  I shall keep trying for 
a bit.


On 06/22/2013 03:12 PM, Robby Findler wrote:

I'm not seeing that behavior (that is a bug, tho). I tried these steps:

1) cmd-t to create a new tab in DrRacket.
2) paste the expression above (there is an automatic "#lang racket" 
inserted).

3) save the file.
4) delete the above expression
5) hit run.

No output observed.

Were you doing something differently?

Robby


On Sat, Jun 22, 2013 at 2:02 PM, Sean Kanaley <mailto:skana...@gmail.com>> wrote:


I don't use modules very much, so this could be the defined
behavior similar to how the ffi module "secretly" (it's actually
documented) doesn't reload foreign libraries unless DrRacket is
restarted, but I didn't notice anything in the documentation.  How
to reproduce:

(module+ test
  (write "?"))

Without even running it, save the file, then delete that
expression.  Now run it (as in ctrl+r), and it will write "?".

 Racket Users list:
http://lists.racket-lang.org/users





  Racket Users list:
  http://lists.racket-lang.org/users


[racket] Modules and File Save Bug?

2013-06-22 Thread Sean Kanaley
I don't use modules very much, so this could be the defined behavior 
similar to how the ffi module "secretly" (it's actually documented) 
doesn't reload foreign libraries unless DrRacket is restarted, but I 
didn't notice anything in the documentation.  How to reproduce:


(module+ test
  (write "?"))

Without even running it, save the file, then delete that expression.  
Now run it (as in ctrl+r), and it will write "?".


 Racket Users list:
 http://lists.racket-lang.org/users


Re: [racket] DSLs and complexity

2013-06-21 Thread Sean Kanaley
A famous Lisp programmer once said (in the context of functional 
programming):


"For alumni of other languages, beginning to use Lisp may be like stepping
onto a skating rink for the first time. It's actually much easier to get 
around on
ice than it is on dry land---if you use skates. Till then you will be 
left wondering

what people see in this sport."

A DSL could be seen as an ice skate, or even an airplane.  Airplanes 
require expensive maintenance, expensive fuel, training to fly, etc, yet 
they make the fastest, safest, longest-range mass transit system on 
Earth.  If the article's author's argument is that airplanes aren't 
worth the complexity...


As a simple example, consider the language "Brainfuck".  It would be 
wise to write a DSL with it called "Scheme", where the domain is /actual 
programming/.  The user would be far more productive.

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Code Reuse, Object Oriented vs Functional

2013-06-20 Thread Sean Kanaley
The definition and essence of "object" is not always agreed upon 
(encapsulation, polymorphism, state, ...), but since you're wondering 
about objects versus functions (purely functional), the "versus" implies 
a difference about an object that makes it impure, or the comparison 
isn't so helpful.  If an object was simply an enhanced pure function it 
would just be better.  So the key is that it is /impure/.


In terms of your first question, multiple dispatch is therefore a 
different kind of concern (polymorphism) than the opposing difference 
between object and function (purity).  One can achieve polymorphism 
either through doing something different based on argument types 
(multiple dispatch) or doing something different based on the actual 
type of thing being operated on (sub-object type of generic object 
method--single dispatch).


If you're doing collision detection, multiple dispatch is useful. You 
can write something like "(cartesian-prod collide? objects)" which 
presumably passes every object paired with every other object to 
collide?, which depending on the object types, handles the collision 
appropriately (e.g. friendly fire is disabled by not detecting player 
missiles hitting friendly infantry).


If instead you want to accelerate a vehicle, you can use the vehicle 
itself with its polymorphic accelerate method "(send vehicle accel)" to 
accelerate either a motorcycle or truck without caring what the actual 
subtype is.  The thing is, multiple dispatch generalizes this (multiple 
dispatch generalizes single dispatch clearly...).  The vehicle 
acceleration is also handled by a multimethod that could be called 
"(accel vehicle)".  It's like collision detection in that it accelerates 
based on the argument type--there just happens to be exactly one argument.


So there's really nothing special about objects and polymorphism *gasp* 
as they are just a gimped way of dispatching compared to multimethods!  
This brings us back to state.  An object (really a closure) is useful 
because it contains state (so does a plain "structure" type, so arguably 
I'm implying the encapsulation is useful as well).  If one is attempting 
to maximize the use of an object/closure, it seems they would have to 
take advantage of this state.  So one would use an object not so much 
for "extensibility" (which is inferior to the kind granted by multiple 
dispatch) but for mutable state.


I must therefore conclude objects are for things like simulations and 
other real-time, especially interactive applications where things change 
over time.  There is also functional-reactive programming, which aims to 
bring "pure state" through functions that take time as an implicit 
parameter, and this has advantages and disadvantages (space/time leaks, 
sometimes getting infinite loops from difficulty reasoning about whether 
an update affects something "immediately" or in the next full "update 
cycle" (e.g. Yampa has both various switches and various comparable 
delayed switches to implement either)).  But ultimately, if one is 
choosing an object-oriented approach, they should be doing it for the 
mutable state (or at least encapsulation).


If you just want polymorphism, multiple dispatch is flat out more powerful.

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] SGL Bindings

2013-06-18 Thread Sean Kanaley
Thank you Jay and Stephan for the information.  So the OpenGL package is 
not the same thing as what you get with (require sgl/gl), which in turn 
is the unwrapped (require sgl)?  And the OpenGL package is the "good" one?


I don't mind the matrix stuff, I just want to avoid strange type errors...

 Racket Users list:
 http://lists.racket-lang.org/users


[racket] SGL Bindings

2013-06-17 Thread Sean Kanaley

Hello all,

I'm attempting to do some 3d targeting by screen position, and it would 
be convenient to use unproject, however I can't figure out the 
parameters.  The OpenGL specs require various matrices to be passed in, 
and Racket wants them of type gl-double-vector, which seems to be a type 
synonym for cvector, but then when I get the matrices of that type with 
glGetFloatv and pass it to unproject it complains it got a cvector 
instead of a double-vector...


Does anybody know how to use unproject?

 Racket Users list:
 http://lists.racket-lang.org/users


Re: [racket] Adding new Rosetta tasks

2013-06-12 Thread Sean Kanaley

Welll that one might be cheating :)

On 06/12/2013 05:25 AM, Tim Brown wrote:

Task: Load and Use a Package from PLaneT

:-)

On 10/06/13 23:08, Sean Kanaley wrote:

What would be the best task to show off Racket's advantages intrinsic to
the language and less to library support?  It would have to somehow 
abuse
hygienic macros I suppose--some kind of task like embedding a DSL, so 
what
would be a good one?  Maybe something with graphics to show off 
functional

composition of pictures--perhaps the task could be to recreate IRL
(imperative robot language)...the state machine with the robot from the
Haskell book The Haskell School of Expression.  Other ideas are 
welcome...


On 06/10/2013 04:17 PM, Daniel Prager wrote:

Sean wrote:
> Also, Racket is one short of Python in popularity. If
> someone could do two more we'll defeat those lazy Python
> programmers, probably with less work!

Also, you can add your new tasks, which opens up another strategy for
advancing the Racket ranking.

Guidelines on new task creation:
http://rosettacode.org/wiki/Rosetta_Code:Add_a_Task

I added my first last night
--http://rosettacode.org/wiki/Deming%27s_Funnel -- together with a 
Racket
solution, shortly followed by a contributed Python approximation (so 
the

Pythonistas aren't totally lazy!) while still in draft.

-- Dan






 Racket Users list:
 http://lists.racket-lang.org/users


Re: [racket] Style or and/define

2013-06-11 Thread Sean Kanaley
This code appears to be equivalent to using Maybe in Haskell, with the 
same kind of indentation issues:


case char-width of
  Nothing -> Nothing
  Just n -> do stuff, get new Maybe, case new-maybe of
 Nothing -> Nothing
 Just x -> do stuff ... etc...

In Haskell, one composes these with bind, which combines the "do stuff" 
portion with the unwrapped Just value, otherwise continues returning 
false forever (which due to laziness is the same as the first cond 
returning #f).


In Racket, one could implement either monads altogether or specifically 
one to handle chaining functions that might return #f.


e.g., instead of cond:

(maybe
   (do something)
   (bind new possibly false value)
   (do something with that value)
   etc.)

 Racket Users list:
 http://lists.racket-lang.org/users


Re: [racket] Rosetta Sokoban Solution

2013-06-11 Thread Sean Kanaley

Hi Jens,

I like the idea of using an object that dispatches on number of 
arguments instead of requiring explicit function names, something I'm 
embarrassed to say I hadn't thought of, so I'm grateful for being shown 
this technique.


I shall go about experimenting with a shorter solution.  I'll be using a 
less "only people that know everything about Racket" object however ;) 
shown here:


(define (level ss)
  (define h (hash-copy (for*/hash ([(s i) (in-indexed ss)]
   [(x j) (in-indexed s)])
 (values (list i j) x
  (case-lambda
[(p) (hash-ref h p)]
[(p x) (hash-set! h p x) x]
[else (error "level: too many arguments")]))

I didn't even know structures could be procedure-ified.

On 06/11/2013 05:06 AM, Jens Axel Søgaard wrote:

Hi Sean

2013/6/10 Sean Kanaley 


Also, for some reason Racket doesn't return values from mutations.  Why on 
earth (set! x 3) is void instead of 3 is a mystery, but it leads to things like:

(define-match (x ...) (heap-min heap))
(now-remove-it!)

and, in addition to verbose naming:

(vector-set! v i 4)
v

which should ideally be:

(vec! v i 3)


Here is an alternative representation of levels using that allows you to
write (l p) to get the value of position p in level l. Also (l p x) sets the
character at position p in level l to x.

#lang racket
(struct level (h get/set)
   #:property prop:procedure (struct-field-index get/set))

(define (make-level strings)
   (define h (hash-copy
  (for*/hash ([(row i) (in-indexed strings)]
  [(x j)   (in-indexed row)])
(values (list i j) x
   (define (get p) (hash-ref h p))
   (define (set p x) (hash-set! h p x) x)
   (define get/set (case-lambda [(p) (get p)] [(p x) (set p x)]))
   (level h get/set))

(define l (make-level (list ""
 "#  #"
 "#  . @ #"
 "")))

(l '(0 0))
(l '(0 0) #\.)
(l '(0 0))

  --
Jens Axel Søgaard



 Racket Users list:
 http://lists.racket-lang.org/users


Re: [racket] racket library for minecraft pi edition

2013-06-10 Thread Sean Kanaley

I found a short write-up on the API.  It shows

setBlocks(x1, y1, z1, x2, y2, z2, blockType, blockData) - set lots of 
blocks all at the same time by providing 2 sets of co-ordinates (x, y, 
z) and fill the gap between with a blockType


If a similar function is available for get blocks, that would speed up 
your code hugely.  Every single command sent over TCP has overhead 
associated with it, so attempting to read 128^3 times over a network is 
going to take a while.  The main advice I can give is to do as much as 
possible per command.  "Reasonable" lisp code will be 1x 
times faster than network commands, so whatever you can do "all at once" 
in lisp will save time, especially if you have to wait for round trips, 
e.g. getting a block to determine how to set another block and sending 
them sequentially like that. Ideally, you'd get a bunch of blocks with 
as few commands as possible, then set a bunch with as few as possible, 
or whatever, but mainly try to avoid the network portion as much as 
possible.


As for the data structure, lisp has multi-dimensional arrays:

http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/fun_make-array.html

(make-array '(128 128 128))

with a variety of keywords to control how its created.  That website in 
general has everything on lisp.


For a modern computer, such data is in no way too large (~2 million * 
size of data...say 64 bits = 8 bytes so 16 MB total).  BUT sending 2 
million TCP commands is too many!


On 06/10/2013 09:01 PM, grant centauri wrote:
hello, i've been exploring the educational possibilities of connecting 
a Lisp language to the Minecraft Pi Edition.  I started by writing a 
tutorial using Common Lisp 
http://www.lincolnix.net/gcentauri/build-tower.html which uses a basic 
connection API I wrote.  This is really my first attempt at a coding 
project, and I'm scraping together understanding of things from a 
variety of sources.


the code i have now establishes a socket connection, and i have 
written a "send-command" function with its own helper functions to 
prepare the proper string for the Minecraft API.  There are only a few 
functions that receive data, so I decided to have each one handle its 
reading of the input socket on its own. this is very basic, and i'd 
actually like to write this in a better way, if possible.  i have only 
included one example function here.  i'd like the writing of this 
library to serve as a tutorial as well, because it has helped me 
understand a lot about some basic programming tasks.  here's the code:


https://gist.github.com/anonymous/5745976

my question is mainly about creating a data structure to represent the 
whole 128x128x128 world, and then sending the "get-block" command to 
the Minecraft server for every coordinate, and retrieving all of the 
integers.  is this feasable?


I have been able to write a function to set a column of blocks 
recursively (see the build-tower tutorial in CL) which performs very 
quickly, even when sent from another machine on the network.  but the 
function i wrote (and must have deleted?) to GET a column of block id 
numbers took a few seconds to complete.  i don't know enough about TCP 
connections and how to send and receive data properly.  i'm also 
unsure of the best way to process this function, as what i'd like to 
end up with is a "world" data structure containing coordinate/block-id 
pairs.  the idea is that then you could write a function to perhaps 
turn all the "water" blocks into "air", draining the oceans and 
rivers.  i don't know if this kind of function even makes sense to try 
with the way the Minecraft API works.  I'm unsure about the size of 
the data, and if it is too big to efficiently operate on in this way.


i'm sure i'll have more questions too.  but i'm hoping to document the 
process of learning about this so other learners can benefit from my 
struggle.


thanks,
-grant



   Racket Users list:
   http://lists.racket-lang.org/users



  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Adding new Rosetta tasks

2013-06-10 Thread Sean Kanaley
What would be the best task to show off Racket's advantages intrinsic to 
the language and less to library support?  It would have to somehow 
abuse hygienic macros I suppose--some kind of task like embedding a DSL, 
so what would be a good one?  Maybe something with graphics to show off 
functional composition of pictures--perhaps the task could be to 
recreate IRL (imperative robot language)...the state machine with the 
robot from the Haskell book The Haskell School of Expression.  Other 
ideas are welcome...


On 06/10/2013 04:17 PM, Daniel Prager wrote:

Sean wrote:
> Also, Racket is one short of Python in popularity. If
> someone could do two more we'll defeat those lazy Python
> programmers, probably with less work!

Also, you can add your new tasks, which opens up another strategy for 
advancing the Racket ranking.


Guidelines on new task creation:
http://rosettacode.org/wiki/Rosetta_Code:Add_a_Task

I added my first last night 
--http://rosettacode.org/wiki/Deming%27s_Funnel -- together with a 
Racket solution, shortly followed by a contributed Python 
approximation (so the Pythonistas aren't totally lazy!) while still in 
draft.


-- Dan



   Racket Users list:
   http://lists.racket-lang.org/users



  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Rosetta Sokoban Solution

2013-06-10 Thread Sean Kanaley
il?
lambda = delete entirely, because pressing ctrl+\ and getting an actual 
lambda is vastly superior, or replace with "\" to keep it simple


On 06/10/2013 02:28 PM, Matthias Felleisen wrote:


On Jun 10, 2013, at 1:49 PM, Sean Kanaley wrote:

But if I had to choose which language seems to actually produce 
better code, I would have to side with PicoLisp. 


I wonder whether we could implement pico as a language and then write

 #lang racket/pico

and just reuse the PicoLisp code.



  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Rosetta Sokoban Solution

2013-06-10 Thread Sean Kanaley
and you need 
to do something, so you use the corresponding library function.  
PicoLisp comes built in with anaphoric stuff as well.  I had to use my 
custom awhen to bind @ where that is often bound for free in Pico, not 
requiring a special conditional with binding (and not requiring 
define-syntax-parameter and syntax-parameterize and 
make-transformer-syntax-binding-case-rules to implement it...). Pico 
consistently has the shorter/shortest solutions and in all my tests, has 
excellent run time performance.  I dare say it's a "better" language and 
it would be, in my opinion, for the reasons I just gave.


My intent wasn't to start some kind of flame war here.  I do like 
Racket, it's teaching languages, the assocated HTDP1&2, the associated 
universe/image library (I used that to do Galton Box on Rosetta), and 
the fact that it's very standardized and comes with decent OpenGL 
bindings that I'm using to make a 3d game that I shall one day post.  
But if I had to choose which language seems to actually produce better 
code, I would have to side with PicoLisp. Just beware dynamic scope.


On 06/10/2013 12:42 PM, Matthias Felleisen wrote:

Thank you for this effort.

This is not a criticism of your code but I will say that Racket code looks 
dense and overbearing compared to PicoLisp, Python, and Tcl. Hmph.




On Jun 10, 2013, at 12:34 PM, Sean Kanaley wrote:


The rather empty page on Sokoban now has a Racket solution.  The creator is 
proud to announce it's the fastest solution (though a couple didn't give run 
times) at ~0.1 seconds.  My thanks to Ryan Culpepper for making the binary heap 
that made this possible.

http://rosettacode.org/wiki/Sokoban#Racket

Also, Racket is one short of Python in popularity.  If someone could do two 
more we'll defeat those lazy Python programmers, probably with less work!

Racket Users list:
http://lists.racket-lang.org/users



  Racket Users list:
  http://lists.racket-lang.org/users


[racket] Rosetta Sokoban Solution

2013-06-10 Thread Sean Kanaley
The rather empty page on Sokoban now has a Racket solution.  The creator 
is proud to announce it's the fastest solution (though a couple didn't 
give run times) at ~0.1 seconds.  My thanks to Ryan Culpepper for making 
the binary heap that made this possible.


http://rosettacode.org/wiki/Sokoban#Racket

Also, Racket is one short of Python in popularity.  If someone could do 
two more we'll defeat those lazy Python programmers, probably with less 
work!


 Racket Users list:
 http://lists.racket-lang.org/users


Re: [racket] set!: eval-ing to lvalues

2013-06-09 Thread Sean Kanaley
Thanks for the explanation.  I suspected it was for efficiency reasons, 
but as I've never implemented a "real" scheme, I don't know the trade 
off.  I wonder how bad it is.  Way back, they invented lisp.  Then they 
said it was too slow for real stuff.  Now they say other languages are 
too weak for real stuff, and lisp's relatively little slowness is made 
up for by its power.  And here we are, saying a powerful feature would 
slow it down!


Is it 2x, 3x, 4x, 10x, infinityx slower to implement some kind of lvalue 
system?  And wouldn't that system be necessary only in code that uses 
the mutation?


On 06/09/2013 08:18 AM, Carl Eastlund wrote:

Sean,

Not every Scheme uses an interpreter with an eval function as its 
primary method of execution, or even at all.  Racket uses a bytecode 
interpreter and a JIT native-code compiler; the eval function simply 
triggers compilation to bytecode.  These give a great deal more 
efficiency than running via eval, and supporting multiple modes of 
execution would be significantly more expensive.  Evaluating to values 
by default, rather than to addresses, also gives the compiler a great 
deal of flexibility. It doesn't need to keep track of the addresses 
where it found things and refer to them there in case they are about 
to be mutated; once they have been "found" via evaluation, they can be 
copied to register and the original address can be forgotten, if 
that's most expedient.  I'm not a compiler implementer myself, so I'm 
sure others can probably give more specific details.  In the meantime, 
I hope this explanation is helpful.


Carl Eastlund

On Thu, Jun 6, 2013 at 4:12 PM, Sean Kanaley <mailto:skana...@gmail.com>> wrote:


Hello all,

I was curious why Scheme and now Racket does not inherently
support a generic set!.  I found an SRFI
http://srfi.schemers.org/srfi-17/srfi-17.html that suggests a
generic method solution requiring a lookup for the "real" setter
(and so needing a special setter for every data type. What is the
disadvantage of simply changing eval to take a "fetch?" parameter
that decides whether to ultimately resolve addresses to values? 
Then set! is evaluated with this as #f and can operate on whatever

that address is.  I have implemented this in a toy interpreter
with the bare minimum of forms plus vectors to test. The
vector-ref type of function gets applied as usual to the vector
and index arguments, except that if it's within a set! as the left
argument where the fetch? is #f and the final fetching of the
address given by vector-ref never happens.

Here's the critical pieces:

1. setting
"update" is what changes the store
set! is of course a clause within eval
the last parameter to eval in the first line says don't fetch

[(set! addr-x x) (match-let* ([(v*s addr s) (eval addr-x e s #f)]
  [(v*s v s) (eval x e s)])
(update addr v s))]

2. evaluating symbols (another clause)
the symbol only returns its address with fetching off

[(sym y) (let* ([addr (lookup y e)]
[val (if fetch? (fetch addr s) addr)])
   (v*s val s))]

3. the "built-in" (part of environment) vector-ref called vec@
"fetch?" will be false if (vec@ ...) is the first argument to set!
"a" is the base address of the vector

(define (vec@-f e s fetch? v i)
...unimportant stuff...
(let ([val (if fetch? (fetch (+ a i) s) (+ a i))])
  (v*s val s)

So long as all built-in types have this conditional fetcher, then
every user type built on top of them won't need a special setter. 
And since this would work just as well for inc! types funtions,

from now on

(vector-set! v i (add1 (vector-ref v i))
is
(inc! (vec@ v i))

I assume this has already been thought of and therefore discarded,
but why?


  Racket Users list:
http://lists.racket-lang.org/users





  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Size matters

2013-06-09 Thread Sean Kanaley
The idea was to provide an extended name for free, so I should've used 
named let.  Named functions of course already have names, e.g.


(define (z x)
  (let q ([x #1])
(let ([x #2])
(+ z:x q:x x)

Plain "let" evaluates in parallel, so in (let ([x y] [x x]) the last x 
is free.  So qualifying like ([x:n is inconsistently naming part of a 
scope, the part pertaining to a single variable, and so it's actually 
just renaming the variable itself.  The qualifier should extend to the 
entire "frame" or whatever it's called for the things it's qualifying.  
Although your code would be perfect for the nested let, "let*".


On 06/09/2013 03:03 AM, ??? ? wrote:

Then why not
(let ([x:n #1])
  (let ([n #2])
(+ x:n n)

I think, it is less confusing


???, 8  2013, 17:07 -04:00 ?? Sean Kanaley :

Sorry about the multiple posts, but an idea just occurred to me to
save on name length in the case of name conflicts, like in the
posted fill-sack example.  Example code:

(let ([n #1])
  (let ([n-that-needs-new-name #2])
(+ n n-that...)

The inner most n will overwrite the outer one if the same name is
used, but sometimes, logically, the same name /should/ be used. 
There's two "n"s at work, and it's the entire point of lexical

scope to provide the proper one.  So there should be a mechanism
to access a different one.  Behold:

(let (x [n #1])
  (let ([n #2])
(+ x:n n)

On 06/08/2013 03:49 PM, Eli Barzilay wrote:

(Possible irrelevant rambling, but I generally am very aware of my
code formatting, and this looked like a good point to highlight.  It's
still probably picking on something that not many people care about as
much as I do...)

The style guide has a section labeled "size matters" -- it also has
another section on names, encouraging using readable names.  Both of
these are perfectly reasonable goals, but they can pull you in
different directions, and I ran into an example that demonstrates it
in a very nice way.  There is also Yaron's quote about favoring
readers, which is IMO more important than both of these -- since they
are just sub-points aiming towards that goal.

I have recently experimented more with taking code compactness more
seriously.  I still keep my own code under 80 characters, which I know
many people don't like, but on the other hand, I always try to fill
the lines as much as possible while maintaining readability.  The idea
is that the principle of favoring readers means that it should be easy
to read code -- and lines that are too long, or suffer from rightward
drift, or names that are too long are all things that delay reading.
I can also see the recent tendency to use `define' where possible as
something that goes to this end too: prefer using the same kind of
binding construct to make it easier to read code.

So to get to my point, there's the decision of what name to use for
your identifiers some people (*ahem*) stick to an always-readable
names, to the point of not using names like `i', `n', and `x'.  I'm on
the complete other side of this -- I strongly prefer these names
because they make code shorted and therefore easier to read.  The same
goes for the style guide's recommendation to name intermediate values
instead of nesting function calls -- it's obviously a line that the
author should decide on (exaggerated examples on both sides are easy,
and contribute nothing), and I tend to go further with nested calls
than defining intermediates.  (This same point applies to naming
functions vs using lambda expressions.)

My point here is that using longer names and binding intermediates can
explain the code better, but it's easy to carry this over to hurting
overall readability.  The example that made me post this is below (no
need to look up who wrote the original code, it's irrelevant since it
*is* following many of the style's guidelines).  The first chunk is
the original code, the second is my rewrite.  There are some obvious
things like using `match' to make the code more concise and more
readable, but note that the `cond' expression in the loop is very hard
to read in the first version -- the descriptive names are long enough
that the overall structure of the loop is not obvious.

In my revision, the much shorter names are less readable, but on the
flip side they allow laying out the code in a way that makes it much
more obvious, and since I started this by just doing mechanical
transformations, it was surprising to see that what the shrunk code is
doing becomes very clear.  This clarity has the obvious advantages,
which is why it's so important

Re: [racket] Size matters

2013-06-08 Thread Sean Kanaley
Sorry about the multiple posts, but an idea just occurred to me to save 
on name length in the case of name conflicts, like in the posted 
fill-sack example.  Example code:


(let ([n #1])
  (let ([n-that-needs-new-name #2])
(+ n n-that...)

The inner most n will overwrite the outer one if the same name is used, 
but sometimes, logically, the same name /should/ be used.  There's two 
"n"s at work, and it's the entire point of lexical scope to provide the 
proper one.  So there should be a mechanism to access a different one.  
Behold:


(let (x [n #1])
  (let ([n #2])
(+ x:n n)

On 06/08/2013 03:49 PM, Eli Barzilay wrote:

(Possible irrelevant rambling, but I generally am very aware of my
code formatting, and this looked like a good point to highlight.  It's
still probably picking on something that not many people care about as
much as I do...)

The style guide has a section labeled "size matters" -- it also has
another section on names, encouraging using readable names.  Both of
these are perfectly reasonable goals, but they can pull you in
different directions, and I ran into an example that demonstrates it
in a very nice way.  There is also Yaron's quote about favoring
readers, which is IMO more important than both of these -- since they
are just sub-points aiming towards that goal.

I have recently experimented more with taking code compactness more
seriously.  I still keep my own code under 80 characters, which I know
many people don't like, but on the other hand, I always try to fill
the lines as much as possible while maintaining readability.  The idea
is that the principle of favoring readers means that it should be easy
to read code -- and lines that are too long, or suffer from rightward
drift, or names that are too long are all things that delay reading.
I can also see the recent tendency to use `define' where possible as
something that goes to this end too: prefer using the same kind of
binding construct to make it easier to read code.

So to get to my point, there's the decision of what name to use for
your identifiers some people (*ahem*) stick to an always-readable
names, to the point of not using names like `i', `n', and `x'.  I'm on
the complete other side of this -- I strongly prefer these names
because they make code shorted and therefore easier to read.  The same
goes for the style guide's recommendation to name intermediate values
instead of nesting function calls -- it's obviously a line that the
author should decide on (exaggerated examples on both sides are easy,
and contribute nothing), and I tend to go further with nested calls
than defining intermediates.  (This same point applies to naming
functions vs using lambda expressions.)

My point here is that using longer names and binding intermediates can
explain the code better, but it's easy to carry this over to hurting
overall readability.  The example that made me post this is below (no
need to look up who wrote the original code, it's irrelevant since it
*is* following many of the style's guidelines).  The first chunk is
the original code, the second is my rewrite.  There are some obvious
things like using `match' to make the code more concise and more
readable, but note that the `cond' expression in the loop is very hard
to read in the first version -- the descriptive names are long enough
that the overall structure of the loop is not obvious.

In my revision, the much shorter names are less readable, but on the
flip side they allow laying out the code in a way that makes it much
more obvious, and since I started this by just doing mechanical
transformations, it was surprising to see that what the shrunk code is
doing becomes very clear.  This clarity has the obvious advantages,
which is why it's so important to "favor readers".

As a sidenote -- there are two named intermediates in this code that I
didn't get rid of: on one hand losing them won't save space (and
therefore I consider removing them as something that would only
obfuscate things), and on the other hand the result would be nesting
the verbose computation into a place where it is not relevant.  (And
yes, there'd be an advantage for having an infix syntax here, IMO...)

(In any case, sorry for the noise.  I'll avoid further replies...)

---

(define (fill-sack (items items) (volume-left 0.25) (weight-left 25) (sack 
null) (sack-value 0))
   (if (null? items)
   (values (list sack) sack-value)
   (let* ((item (first items))
  (item-wgt (item-weight item))
  (max-q-wgt (floor (/ weight-left item-wgt)))
  (item-vol (item-volume item))
  (max-q-vol (floor (/ volume-left item-vol
 (for/fold
 ((best-sacks (list sack))
  (best-sack-value sack-value))
   ((qty (in-range 0 (add1 (min max-q-vol max-q-wgt)
   (let-values (((inner-best-sacks inner-best-sack-value)
  

Re: [racket] Size matters

2013-06-08 Thread Sean Kanaley
I was coincidentally just thinking about this.  I'm experimenting with 
terse names myself right now.


I believe the general rule for consistent pain/gain is that the favoring 
of the short name is proportional to both how frequently it's used and 
how obvious it is.  For-loops in C had better default to using "i", 
because saying "index" isn't helpful.  If one doesn't understand how a 
for loop works so that "i" is somehow unclear in its purpose, one has no 
chance of understanding the code anyway. Similarly, Racket 
comprehensions can use "x" seeing as the type of the list should already 
be known or the whole thing is incomprehensible in the first place!  
Expanding from this, there is a sort of scope at work one might call 
"meaning or type scope".  The "x" bound to elements of a list is 
necessarily an element typed to whatever that list is made up of (except 
for heterogeneous lists, see below).  If that in turn is a structure, 
something bound to some component of that structure is whatever /that/ 
type is.  If the list is "things-to-print" then any name is already 
redundant because we know x is a "thing-to-print".  Similarly, One can 
bind "p" to the result of a struct access inside another when accessing 
a point in space from the other.  For the code to work /at all/, p must 
be of type "point", so it's easy to remember.  The only reason it's even 
named is because the programmer decided he/she needed to re-use that 
name, so rather than type the whole accessing code to get to "p", he/she 
provided a name.  The very fact that it was named in this manner 
suggests the need for immediate reuse and thus ease of remembrance.  
This would fail to be true if it /wasn't/ reused immediately, in the 
static/lexical sense, but then it's for all intents and purposes a 
global variable!  It's either local and not confusing or /not /local and 
/confusing./  The latter case implies either poor code or the need for 
an actual descriptive name.  That is, do not use "i" for something that 
is used at 100-line intervals in your code!  Might forget that "i" is 
bound and end up shadowing it inadvertently, or in my experience, the 
far worse case that happens when you /un/shadow after changing the local 
"i", but perhaps not everywhere needed, and weird results ensue 
depending on which one is scoped.  Either avoid sharing a variable 
between what is hopefully multiple functions if the references are that 
far apart (making it global-ish), shorten the functions, or, if really 
necessary to have this sharing, give it a real name, like 
super-important-reference-that-i-can't-figure-out-how-to-keep-local-cause-i'm-dumb 
(Racket provides define-values, let, and an object system, all of which 
share locally to multiple functions.).  In summary, if short names are 
confusing the code was already bad!


*About heterogeneous lists.  Sometimes, one wants the equivalent of 
multiple return values without the inconvenience, like a list of list of 
3 things that are associated instead of 3 "unzipped" lists that now have 
to be bound with (let-values ([( ... which is rather heavy, and 
recombined by zipping them.  This someone might not care to define a 
struct for this list of 3 things to make a nice typed homogeneous list 
for simple utility functions that do 2 or 3 things in parallel, but as 
mentioned, can't simply return 2 or 3 things because a list cannot 
contain multiple values directly.  It's not so bad to just remember that 
car = some type and cadr = some other type and caddr = last type.  Or 
maybe I should try harder and come up with a better solution.  Accessing 
by position is dangerous anyway, so the concision gained by (match-let 
([( or car/cadr/caddr is perhaps roughly cancelled by the need to modify 
the underlying representation, requiring a rewrite of every single 
by-position access.  SICP always recommended procedures for accessing.  
So yes, there's a balance between concision, readability, 
comprehensibility, modifiability, etc.  But I believe the balance is in 
favor of helping the programmer read and understand the code, which to 
me means concision, killing three birds with one stone.


On 06/08/2013 03:49 PM, Eli Barzilay wrote:

(Possible irrelevant rambling, but I generally am very aware of my
code formatting, and this looked like a good point to highlight.  It's
still probably picking on something that not many people care about as
much as I do...)

The style guide has a section labeled "size matters" -- it also has
another section on names, encouraging using readable names.  Both of
these are perfectly reasonable goals, but they can pull you in
different directions, and I ran into an example that demonstrates it
in a very nice way.  There is also Yaron's quote about favoring
readers, which is IMO more important than both of these -- since they
are just sub-points aiming towards that goal.

I have recently experimented more with taking code compactness more
seriously.  I still keep my own code 

Re: [racket] issue with function "regexp-replaces"

2013-06-07 Thread Sean Kanaley

(regexp-replace* "\n" input-string "\n")

would be the target expansion for those pairs.

On 06/07/2013 08:57 AM, Sanjeev K Sharma wrote:

I have to clean up a bunch of source files that don't show properly

I have a file from which I'm reading a bunch of regular expressions to replace, 
things like this:

(#px"(?i:%5C)""/")

but included in the same file (full of from-to pairs) are a bunch of straight 
string replacements, like this:

("…""\\…")


I cannot figure out what's wrong with this one: what to do here

("\n""\n")

it replaces the starting "\n" but never puts in the replacement "\n"

I've doubled/tripled/quadrupled on the backslashes

("\n""\\n")
("\n""\\\n")

but that doesn't put in a newline, rather two separate characters,  "backslash" and 
"n"

any hints what I'm doing wrong here?

   Racket Users list:
   http://lists.racket-lang.org/users



 Racket Users list:
 http://lists.racket-lang.org/users


[racket] set!: eval-ing to lvalues

2013-06-06 Thread Sean Kanaley
Hello all,

I was curious why Scheme and now Racket does not inherently support a
generic set!.  I found an SRFI
http://srfi.schemers.org/srfi-17/srfi-17.htmlthat suggests a generic
method solution requiring a lookup for the "real"
setter (and so needing a special setter for every data type.  What is the
disadvantage of simply changing eval to take a "fetch?" parameter that
decides whether to ultimately resolve addresses to values?  Then set! is
evaluated with this as #f and can operate on whatever that address is.  I
have implemented this in a toy interpreter with the bare minimum of forms
plus vectors to test.  The vector-ref type of function gets applied as
usual to the vector and index arguments, except that if it's within a set!
as the left argument where the fetch? is #f and the final fetching of the
address given by vector-ref never happens.

Here's the critical pieces:

1. setting
"update" is what changes the store
set! is of course a clause within eval
the last parameter to eval in the first line says don't fetch

[(set! addr-x x) (match-let* ([(v*s addr s) (eval addr-x e s #f)]
  [(v*s v s) (eval x e s)])
(update addr v s))]

2. evaluating symbols (another clause)
the symbol only returns its address with fetching off

[(sym y) (let* ([addr (lookup y e)]
[val (if fetch? (fetch addr s) addr)])
   (v*s val s))]

3. the "built-in" (part of environment) vector-ref called vec@
"fetch?" will be false if (vec@ ...) is the first argument to set!
"a" is the base address of the vector

(define (vec@-f e s fetch? v i)
...unimportant stuff...
(let ([val (if fetch? (fetch (+ a i) s) (+ a i))])
  (v*s val s)

So long as all built-in types have this conditional fetcher, then every
user type built on top of them won't need a special setter.  And since this
would work just as well for inc! types funtions, from now on

(vector-set! v i (add1 (vector-ref v i))
is
(inc! (vec@ v i))

I assume this has already been thought of and therefore discarded, but why?

  Racket Users list:
  http://lists.racket-lang.org/users


Re: [racket] Rosetta code submission / string operations

2013-06-04 Thread Sean Kanaley
Hello fellow Rosetta submitter!

The regular expressions are actually pretty useful to make a functional
version shorter than the imperative one!

First, forms with (for ...) and a bunch of (set!)'s is made functional by
(for/fold ...) where the final (values ...) functionally sets the new
values.
Second, the regexp portion can take a converted symbol instead of a
hard-coded string to save duplicate names.

I present the following compactified implementation:

(define-values (cei cie ie ei)
  (for/fold ([cei 0] [cie 0] [ie 0] [ei 0])
([line (file->lines "unixdict.txt")])
(define-syntax-rule (tally x ...)
  (values (if (regexp-match? (symbol->string 'x) line) (add1 x) x) ...))
(tally cei cie ie ei)))

(print-rule "I before E when not preceded by C" (- ie cie) (- ei cei))
(print-rule "E before I when preceded by C" cei cie)

Since the macro would be needlessly complicated with extra conditional
logic to avoid counting "cei" as "ei", it's better to just subtract at the
end.

I was wondering if there is some way to combine things like define-values
and for/fold...in general I find that whenever I use the functional forms
of (for...), since I will by definition care about the return values, it's
inconvenient, especially in the multiple values case, to rebind the results
to the accumulators in the for form (as seen in the above example).  In
other words, since the results of the functional versions of (for...) HAVE
to be in some way bound eventually (unless it's the entire program), it may
as well perform the binding outright and save the duplication of (let
([result (for ...)]) ...).  Perhaps anaphoric for (afor...) that binds "it"
or something like that, and for multiple values, it0, it1 ...

On Tue, Jun 4, 2013 at 9:34 AM, Tobias Hammer  wrote:

> Sorry for the misinformation but Eli is of course right that regexp-quote
> must be used.
>
> Example:
>
> (regexp-match? "a" "abc")
>
>> #t
>>
> (regexp-match? "." "abc")
>
>> #t  ; WRONG! '.' matches every character
>>
>
> (regexp-match? (regexp-quote "a") "abc")
>
>> #t
>>
> (regexp-match? (regexp-quote ".") "abc")
>
>> #f
>>
>
>
> On Tue, 04 Jun 2013 13:57:41 +0200, Daniel Prager <
> daniel.a.pra...@gmail.com> wrote:
>
>  Thanks Tobias & Eli
>>
>> I've updated my submission to use (regexp-match? sub-str str).
>>
>> [Also added the stretch goal solution, but could do with some refactoring
>> to reduce the joint line-count.]
>>
>> -- Dan
>>
> 
>  Racket Users list:
>  http://lists.racket-lang.org/**users 
>

  Racket Users list:
  http://lists.racket-lang.org/users


  1   2   >