![]() |
Jupyter at Bryn Mawr College |
|
|
Public notebooks: /services/public/dblank / CS245 Programming Languages / 2014-Fall / Notes |
Examples of Lisp, and discussion of video of final project
How does Common Lisp differ from Scheme? Typically:
How does Hy Lisp differ from Common Lisp?
Bonus: up to 10%, examples:
Due: Monday, Dec 15, 2014 8am
Notebook on Hy Lisp:
http://nbviewer.ipython.org/github/bollwyvl/hy_kernel/blob/master/notebooks/Tutorial.ipynb
%%file ~/.ipython/kernels/hy/kernel.json
{
"argv": ["python", "-m", "hy_kernel.hy_kernel", "-f", "{connection_file}"],
"display_name": "Hy Lisp",
"language": "hy",
"codemirror_mode": "hy",
"language_info": {
"name": "hy",
"codemirror_mode": {
"name": "hy"
},
"mimetype": "text/x-hylang",
"pygments_lexer": "ipython3"
},
"help_links": [
{
"text": "Hy Documentation",
"link": "http://docs.hylang.org/"
},
{
"text": "Hy Google Group",
"link": "https://groups.google.com/forum/#!forum/hylang-discuss"
},
{
"text": "Hy Github",
"link": "https://github.com/hylang/hy"
}
]
}
(defn simple-conversation ()
(print "Hello! I'd like to get to know you. Tell me about yourself!")
(setv name (raw_input "What is your name? "))
(setv age (raw_input "What is your age? "))
(print (+ "Hello " name "! I see you are "
age " years old."))
None)
(simple-conversation)
(defn fact (n)
(if (= n 1)
1
(* n (fact (- n 1)))))
(fact 5)
((let [[x 5]]
(lambda () (+ x 1))))
(defn display (v) (print v) 'ok)
(try
(display (fact 900))
(catch [e Exception] 'ok)
;; (else (print "no errors"))
(finally 'ok)
)
(defn display (v) (print v) 'ok)
(try
(display (fact 1000))
(catch [e Exception] 'ok)
;; (else (print "no errors"))
(finally 'ok)
)
sh
is a Python library that wraps up shell commands as Python functions.
In Python, you would write:
from sh import cat, grep, wc
wc(grep(cat("/usr/share/dict/words"), "-E", "^hy"), "-l")
(import [sh [cat grep wc]])
(wc (grep (cat "/usr/share/dict/words") "-E" "^hy") "-l")
(-> (cat "/usr/share/dict/words") (grep "-E" "^hy") (wc "-l"))
From hy_kernel.py:
class HyKernel(IPythonKernel):
def do_execute(self, code, *args, **kwargs):
'''
Generate python code, and have IPythonKernel run it, or show why we
couldn't have python code.
'''
try:
tokens = tokenize(code)
_ast = hy_compile(tokens, '__console__', root=ast.Interactive)
_ast_for_print = ast.Module()
_ast_for_print.body = _ast.body
code = astor.codegen.to_source(_ast_for_print)
except Exception as err:
if (not hasattr(err, 'source')) or not err.source:
err.source = code
# shell will find the last exception
self.shell.showsyntaxerror()
# an empty code cell is basically a no-op
code = ''
return super(HyKernel, self).do_execute(code, *args, **kwargs)
(defmacro -> [head &rest rest]
(setv ret head)
(for* [node rest]
(if (not (isinstance node HyExpression))
(setv node `(~node)))
(.insert node 1 ret)
(setv ret node))
ret)
(define-syntax ->
[(-> ?a) ?a]
[(-> ?a (?b . ?args) . ?rest)
(-> (?b ?a . ?args) . ?rest)])
(-> '"hello" (+ "!") .upper str)