What is the racket translation of this piece of lisp code? - scheme

;; loads a board from the given file
;; it expects the board to be in the format of a single S-expression:
;; a list of nine lists, each containing 9 numbers
(defun get-board-from-file file
(let ((in (open file :if-does-not-exist nil)))
(when in (return-from get-board-from-file (read in)))
(when (not in) (format t "~%Unable to open file ~A" file))
)
)
This is part of a soluton for a sudoku solver.

Try the following, it's a functional equivalent of the Lisp code in the question, but written in Racket:
(define (get-board-from-file file)
(with-handlers ([exn:fail:filesystem?
(lambda (exn) (printf "~%Unable to open file ~A" file))])
(call-with-input-file file
(lambda (in) (read in)))))
The above code handles an exception if the file doesn't exist, and makes sure that the port is closed after the file is read.

Related

Typed racket require module repeated evaluation

This is a follow-on to this answer to this question.
When this code is saved to a file and run from the command line, it prints 13 three times. Twice I can understand, but three times? Why?
When I run it from racket-mode in emacs it prints 13 five times!
And when I run it in DrRacket it prints 13 seven times!
The behaviour is also different in vanilla Racket? Changing #lang typed/racket to #lang racket prints 13 once from the command line, twice from emacs and three times from DrRacket.
What's going on here?
#lang typed/racket
(module for-syntax-mod typed/racket
(provide foo)
(: foo (-> Real Real))
(define (foo n)
(+ n 3)))
(require (for-syntax 'for-syntax-mod))
(begin-for-syntax (println (foo 10)))

Can't load Simply Scheme code

I'm having trouble with loading the code for the Berkeley Scheme course Simply Scheme, specifically this code. I've tested it in many different versions of Scheme. In Chicken, I get this error:
#;1> (load "simply.scm")
; loading simply.scm ...
Error: (symbol->string) bad argument type - not a symbol: #<procedure (? wd)>
Call history:
<syntax> (##core#if (empty? x) (##core#begin (whoops "Invalid argument to FIRST: " x)) (##core#if (word? x) (......
<syntax> (empty? x)
<syntax> (##core#begin (whoops "Invalid argument to FIRST: " x))
<syntax> (whoops "Invalid argument to FIRST: " x)
<syntax> (##core#if (word? x) (##core#begin (word-first x)) (##core#begin (whoops "Invalid argument to FIRST:...
<syntax> (word? x)
<syntax> (##core#begin (word-first x))
<syntax> (word-first x)
<syntax> (##core#begin (whoops "Invalid argument to FIRST: " x))
<syntax> (whoops "Invalid argument to FIRST: " x)
<syntax> (##core#undefined)
<syntax> (word->string word->string)
<eval> (word->string word->string)
<eval> (string? wd)
<eval> (number? wd)
<eval> (symbol->string wd) <--
Just for comparison, Racket gives this error:
Welcome to Racket v6.3.
> (load "simply.scm")
simply.scm:20:12: set!: cannot mutate module-required identifier
in: number->string
context...:
/home/hercynian/racket/collects/racket/private/misc.rkt:87:7
. . . which doesn't seem to be the same thing. This is beyond my rank beginner skills to fathom. Any ideas what's wrong with simply.scm?
It seems to work with:
guile (2.0.11),
chicken's intepreter (4.10.0),
gambit's interpreter gsi (4.2.8),
mit-scheme (9.1.1)
Racket will not do, afaik you'd have to modify this file quite heavily (at least change set! to define and probably wrap it all in module? -- but I'm no racket guy)
Here's what I would do:
download this simply.scm file once again, just to be sure (your chicken error suggests somewhere you miss "let", maybe in line 264 (def. of word) or 310 (def. of first)?),
try the above scheme implementations, in case you do get any errors, paste them here,
in case you don't have these versions (which would be weird, but I don't know your situation), and are doing the course on your own, try to do it without simply.scm, and any time you find something's missing in your scheme, try to copy only that definition from simply.scm (or modify your code so that it's not needed) -- that's the hardcore way.
I see from the error that you are using DrRacket IDE or racket binary.
Racketeer and SO-er Danny Yoo has made a Racket module language to support Simply Scheme in the racket language suite. In Racket with the bottom left dropdown set to "Determine language from source" and replace the definitions window, including the #lang line to the following:
#lang planet dyoo/simply-scheme:2
(se (butlast (bf "this"))
"world")
And press RUN. It will download and install the language and then you'll see the answer (hi "world"). The first time around you might see an error, but my experience is that it will go away on a consecutive run.
The definitions will have all the simply scheme features described in the the documentation. Happy hacking!

How to print racket check-expect results in terminal

I have the following racket code:
(require test-engine/racket-tests)
(define (square val)
(* val val))
(check-expect (square 3) 9)
When I execute the script in DrRacket using the Beginning Student language, I get the following output in the application console (the view is called “Interactions” in DrRacket):
The test passed!
When I execute the same script in the Terminal via racket my_script.rkt I do not see any output. I checked racket --help but I don’t see any viable option. How can I execute the script in the Terminal and have the same line printed out?
The following works for me in both DrRacket and in the terminal:
#lang racket/base
(require test-engine/racket-tests)
(define (square val)
(* val val))
(check-expect (square 3) 9)
(test)
and prints
The only test passed!
Note that had to add (test) to make this happen, both in DrRacket and on the command line, according to this doc.

How would I make this Racket code DRYer?

I'm porting a Python script to Racket as a learning experience, and I have this function:
(define (check-status)
(define git [find-executable-path "git"])
(define-values (ckot out in err)
(subprocess #f #f #f git "checkout" "-q" "master"))
(define-values (local lout lin lerr)
(subprocess #f #f #f git "rev-parse" "#"))
(define-values (remote rout rin rerr)
(subprocess #f #f #f git "rev-parse" "#{u}"))
(define-values (merge-base mbout mbin mberr)
(subprocess #f #f #f git "merge-base" "#" "#{u}"))
(display-lines (port->lines mbout))
(define ports '(ckot out in err local lout lin lerr remote rout rin rerr merge-base mbout mbin mberr))
(map (lambda (x)
(cond ((input-port? x) (close-input-port x))
((output-port? x) (close-output-port x)))) ports))
The problem is that it's not very DRY. Since I'm using a Lisp, and Lisp is known for being able to do crazy things, I want to know if there's a way to take all the subprocess code and extract it so I can do something like:
(define (check-status)
(define commands '(
'("checkout" "-q" "master")
'("rev-parse" "#")
'("rev-parse" "#{u}")
'("merge-base" "#" "#{u}"))
(map currently-immaginary-git-command-fn commands))
and end up with a list of the output of each command in the list of commands. How would I do this? Since I'm new to the whole Lisp/Scheme thing, I'm figuring out the syntax as I go and I'm not fully aware of the resources available to me.
First of all, good for you for wanting to come up with a cleaner solution! You're right that there's a more elegant way to do what you've attempted.
To start, using subprocess is almost certainly overkill in your particular use-case. The racket/system module provides a simpler interface that should be sufficient for your needs. Specifically, I'd use the system* function, which executes a single process with the provided arguments, then prints its output to stdout.
Using system*, it's possible to create a very general helper function that can execute a command for a particular executable and returns its output as a string.
(define (execute-command proc-name)
(define proc (find-executable-path proc-name))
(λ (args)
(with-output-to-string
(thunk (apply system* proc args)))))
This function itself returns a new function when it's called. This means that using it to call a Git command would look like this:
((execute-command "git") '("checkout" "-q" "master"))
The reason for this will become apparent shortly.
Actually looking at the implementation of execute-command, we use with-output-to-string to redirect all of the output from the system* call into a string (instead of just printing it to stdout). This is actually just an abbreviation for using parameterize to set the current-output-port parameter, but it's simpler.
With this function, we can implement check-status very easily.
(define (check-status)
(define commands
'(("checkout" "-q" "master")
("rev-parse" "#")
("rev-parse" "#{u}")
("merge-base" "#" "#{u}")))
(map (execute-command "git") commands))
Now the reason for having (execute-command "git") return a new function becomes apparent: we can use that to create a function which will then map over the commands list to produce a new list of strings.
Also, note that the definition of the commands list only uses a single ' at the beginning. The definition you provided would not work, and in fact, the ports list you defined in your original implementation is not what you'd expect. This is because '(...) is not exactly the same as (list ...)—they are different, so be careful when using them.

Scheme: Proper application of the eval function?

at work I encountered a basic problem when trying to implement a configuration script with Scheme. To avoid the need of inventing an artificial and restricted language the script should contain actual code. This code shall be evaluated later on. To make the configuration work as desired it has to have access to certain variables. These variables are only known in the context of the evaluation. Therefore the configuration script has to be evaluated in the current environment. Here is a primitive example of what I am talking about:
(let ((a #t))
(wr "a is ..."
(eval '(if a "true" "false"))))
When running this code I'd always get an error message telling me that the variable 'a' is unknown. So the question is: Do you know how to evaluate frozen code inside the current environment?
P.S.: I use the bigloo compiler.
/////////////////////////////////////////////
EDIT: //////////////////////////////////////////////////////
When using the approach suggested by Chris I came to another interesting problem, the usage of the case keyword. The following two examples both use the same case construction which should trigger the output of a "yes!" line. Unfortunately they behave differently.
Usual -> output is "yes!" as expected:
(define testit "test")
(case testit
(("test")
(begin (newline) (write "yes!") (newline)))
(else
(begin (newline) (write "no!") (newline)))))
With eval -> output is surprisingly "no":
(define env (null-environment 5))
(eval '(define testit "test") env)
(eval '(case testit
(("test")
(begin (newline) (write "yes!") (newline)))
(else
(begin (newline) (write "no!") (newline)))))
Does that make any sense?
eval cannot access lexical variables, such as those defined using let.
Instead, you have to create an environment, and populate it with the variables you want to make available. For example:
(define env (null-environment 5))
(eval '(define a #t) env)
(wr "a is ..."
(eval '(if a "true" "false") env))
To answer your edit, you aren't passing env as an argument to the last eval. testit doesn't exist in the environment that eval creates if that argument isn't given.
That may be a typo, but if not, that's your problem.

Resources