How to implement try-catch block in racket? - exception

I try to write a try-catch block in racket, from the boilerplate provided here, however when I run it throws me an error.
try-catch block:
#lang racket
(require try-catch-match)
(try [(displayln "body")
(raise 'boom)]
[catch (string? (printf "caught a string: ~v\n" e))
(symbol? (printf "'e' (the value of the exception) is: ~v\n" e))])
Throws this error:
It says syntax error, but I really cannot see any issues. The code is from the official racket website. My goal is to write a simple try-catch block in racket, presumably using the imported library.

You're requiring try-catch-match library, but your example comes from try-catch library. These two are different and if you use the correct one, the example code will work:
#lang racket
(require try-catch)
(try [(displayln "body")
(raise 'boom)]
[catch (string? (printf "caught a string\n"))
(symbol? (printf "caught a symbol\n"))])

Related

not found Calls: <Anonymous> error when knitting from r studio to HTML

{r,eval=F}
corfit <- duplicateCorrelation(brain.rma, design.trt, block = blocks)
{r histOfcorrelations}
print(cor)
{r}
plot(hist(tanh(corfit$atanh.correlations)))
My codes run just fine in the RMD file, but will not knit to HTML.
Error in hist(tanh(corfit$atanh.correlations)) : object 'corfit' not
found Calls: ... withCallingHandlers -> withVisible ->
eval -> eval -> plot -> hist Execution halted
Any suggestions?
Thanks!
I think that it might be because your statement eval=F.
This in fact makes knitr not to evaluate corfit and then the object can't be found.
Try to delete eval=F and see what happens!
You need to remove your code: "eval=F"
eval = FALSE prevents code from being evaluated. (And obviously if the code is not run, no results will be generated). This is useful for displaying example code, or for disabling a large block of code without commenting each line.
https://yihui.org/knitr/options/#code-evaluation

Run Lisp functions on load

Whenever I (load "program.lisp") using the following code I get the error: "Error: Unexpected end of #input stream "program.lisp"
(defun theProgram ()
(reset)
(print "Hello Kappa")
(setentries)
(startloop)
(loop for x in mylist collect (splitremove))
(loop for x in numlist collect (getgrades))
(loop for x in namelist collect (getprint))
(loop for x in printlist collect (andprint)))
(theProgram)
I know the last line is the problem and it will work fine if it is not included however I need the program to startup on load, how can I achieve this?
Edit: I should note that setentries calls a (read) and so does startloop. I am using GNU common lisp 2.6 with gcl interpreter.
The actual error was that the (read) part in the functions did not have stream declared so it was reading the input from the script as it was running rather than from the terminal.

Can't get pprint to work in clojure

Noob question, using Win7 64-bit, Clojure 1.2.0, Java 1.6.0_22
When I start clojure from command line, pprint function is easily available.
user=> pprint
#<pprint$pprint clojure.pprint$pprint#16dfa45>
user=> (pprint "hi")
"hi"
nil
user=>
But when I try to use pprint from a file, I get an error. This happens with and without namespace (ns... :require...) as shown in pprint documentation
clj file as follows:
(ns whatevah
(:require clojure.pprint))
(pprint "hi")
Error as follows:
C:\Users\mischw\code\Clojure>java -cp ";c:\users\mischw\code\clojure\classes\*;c:\Program Files (x86)\Java\SWT;c:\users\mischw\code\clojure\classes\bookcode\*" clojure.main swinglearn.clj
Exception in thread "main" java.lang.Exception: Unable to resolve symbol: pprint in this context (swinglearn.clj:14)
... 21 more
Output completed (0 sec consumed) - Normal Termination
I don't understand the general idea of what's going on here. Why does one work but not the other? Does that have to do with namespaces? Classpaths? Some other simple fix? Clearly noob questions, but I find this happens with a bunch of examples... I'm unable to run them even though it seems straightforward to import/use/require/include them.
You're getting require mixed up with use and/or import. require causes the library to get loaded, and every public symbol it exports will be accessible as eg clojure.pprint/pprint. If you want to use a more convenient name like just pprint, you need to refer to the namespace. use is a convenient shorthand for "require, then refer", to load the library without the namespace prefix.
user> (ns user (:require clojure.pprint))
nil
user> (pprint 1)
; Evaluation aborted.
user> (clojure.pprint/pprint 1)
1
nil
user> (ns user (:use clojure.pprint))
nil
user> (pprint 1)
1
Edit: Not sure why it's working for you from the REPL. As you can see, it doesn't work for me. I imagine you did some setup earlier that makes it work and then forgot about it, or possibly you have some init script that does this stuff for you at the REPL but not when loading from a file.
Here are a couple of examples:
;;how to use it with :require and :use
;; :require
(ns example.pprinter
(:require [clojure.pprint :as pp]))
(def myname "John Smith")
(pp/pprint myname)
;; :use
(ns example.pprinter
(:use clojure.pprint))
(def myname "John Smith")
(pprint myname)

Is there a simple method for writing traces from multiple sbcl threads to standard output through MCLIDE/swank?

Using SBCL, I'm writing a small server and I would like to trace the server thread, but when I use mclide/swank, I do not see any output from the server thread.
? (require 'sb-posix)
NIL
? (sb-thread:make-thread (lambda () (format t "hi from the thread")))
?
When I try the same thing from sbcl directly, I see what I expect:
(require 'sb-posix)
; loading system definition from
; /opt/local/var/macports/software/sbcl/1.0.39_0+html+threads/opt/local/lib/sbcl/sb-grovel/sb-grovel.asd
; into #
; registering # as SB-GROVEL
("SB-POSIX" "SB-GROVEL" "ASDF")
(sb-thread:make-thread (lambda () (format t "hi from the thread")))
hi from the thread#
*
Does swank have issues capturing standard output from non-foreground threads? If I used slime, would this kind of thing work?

Compojure HTML Formatting

I'm relatively new to Clojure and a complete HTML/Compojure virgin. I'm trying to use Compojure to create static pages of HTML using a function similar to this:
(defn fake-write-html
[dir args]
(let [file (str dir *file-separator* *index-file*)
my-html (html
(doctype :html4)
[:html
[:head
[:title "Docs and Dirs:"]]
[:body
[:div
[:h2 "A nice title"]]
[:div
[:ul
[:li "One"]
[:li "Two"]]]]])]
(clojure.contrib.duck-streams/spit file my-html)))
The function just writes HTML to a file. (The args argument is irrelevant here. Just there to assure the example compiles and runs in my program.)
"Programming Clojure" indicated that the call to the html function would produce formatted HTML -- multiple lines with indentation. All I get is the doc type as expected followed by all of the HTML on a single line. HTML Tidy doesn't find any issues with the content of the output file. It comes out as a single line if I println it at the REPL too.
Is there something else needed to get formatted output?
The formatting of HTML output in Compojure was removed for performance and complexity reasons. To get formatted output you will probably have to write your own printer function.
I usually output HTML as Compojure sees fit and use Firebug to view it live in my browser. Firebug will display it nicely formatted no matter if it's really all on one line or not. This works well enough most of the time. If you need to serialize this HTML in a readable form, you could keep it as Clojure vectors and sexps and serialize it that way.
Although Brian's answer pointed me to Firebug, enabling the debugging I wanted, I was just to obsessive-compulsive to leave it alone. Following up on kwertii's pointer to JTidy, I included the following code in my program.
Edit: Simplified the code somewhat
(ns net.dneclark.someprogram
(:gen-class)
...
(:import (org.w3c.tidy Tidy))
)
...
(defn configure-pretty-printer
"Configure the pretty-printer (an instance of a JTidy Tidy class) to
generate output the way we want -- formatted and without sending warnings.
Return the configured pretty-printer."
[]
(doto (new Tidy)
(.setSmartIndent true)
(.setTrimEmptyElements true)
(.setShowWarnings false)
(.setQuiet true)))
(defn pretty-print-html
"Pretty-print the html and return it as a string."
[html]
(let [swrtr (new StringWriter)]
(.parse (configure-pretty-printer) (new StringReader (str html)) swrtr)
(str swrtr)))
I added the jtidy-r938.jar to my project (NetBeans using the enclojure plugin) and imported it. The configuration function tells the parser to output formatted, indented HTML and skip the warnings. The return value from the pretty-printer function is now nicely formatted whether I open it with Firebug or a simple text editor.
There are tons of HTML pretty printers available for Java, notably JTidy, a Java port of HTML Tidy. You can easily feed Clojure's output through this library programatically and get neatly indented and formatted HTML back.
HTML Tidy is also available as a command-line program for Unix if you'd care to go that route -- you can just pipe your HTML through it like any other shell program.
The above did not work for me.
I changed this a bit.
add this [jtidy "4aug2000r7-dev"] to project.clj
(:use clojure.core)
(:import (org.w3c.tidy Tidy))
(:import (java.io ByteArrayInputStream ByteArrayOutputStream)))
(defn configure-pretty-printer
"Configure the pretty-printer (an instance of a JTidy Tidy class) to
generate output the way we want -- formatted and without sending warnings.
Return the configured pretty-printer."
[]
(doto (new Tidy)
(.setSmartIndent true)
;(.setTrimEmptyElements true)
(.setShowWarnings false)
(.setQuiet true)))
(defn pretty-print-html
"Pretty-print the html and return it as a string."
[html]
(let [swrtr ( ByteArrayOutputStream.)]
(.parse (configure-pretty-printer) (ByteArrayInputStream. (.getBytes (str html))) swrtr)
(str swrtr)))
If anyone is still looking at this query, you need the hiccup library. If formats HTML from exactly the Clojure data structure shown.
So
(require '[hiccup.core :refer [html]])
(defn fake-write-html
[dir args]
(let [file (str dir *file-separator* *index-file*)
my-html (html
[:html
[:head
[:title "Docs and Dirs:"]]
[:body
[:div
[:h2 "A nice title"]]
[:div
[:ul
[:li "One"]
[:li "Two"]]]]])]
(clojure.contrib.duck-streams/spit file my-html)))
will work exactly as the original poster intended. Strongly recommended.