<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Drinkable Chicken &#187; Python vs Scheme</title>
	<atom:link href="http://4.flowsnake.org/archives/tag/python-vs-scheme/feed" rel="self" type="application/rss+xml" />
	<link>http://4.flowsnake.org</link>
	<description>A Pythoneer&#039;s adventures with Scheme, etc.</description>
	<lastBuildDate>Fri, 15 Jul 2011 08:53:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Python vs Scheme: lists</title>
		<link>http://4.flowsnake.org/archives/1035</link>
		<comments>http://4.flowsnake.org/archives/1035#comments</comments>
		<pubDate>Tue, 16 Nov 2010 19:43:36 +0000</pubDate>
		<dc:creator>Hans Nowak</dc:creator>
				<category><![CDATA[Python vs Scheme]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[scheme]]></category>

		<guid isPermaLink="false">http://4.flowsnake.org/?p=1035</guid>
		<description><![CDATA[I have resumed my &#8220;Python vs Scheme&#8221; series. The latest installment can be found on my new blog. (I&#8217;m announcing it here because otherwise nobody would notice. &#60;0.5 wink&#62;) As always, comments and corrections are welcome. ^_^]]></description>
			<content:encoded><![CDATA[<p>I have resumed my &#8220;Python vs Scheme&#8221; series. The latest installment can be found on my <a href="http://6.flowsnake.org/pvs-lists.html">new blog</a>. (I&#8217;m announcing it here because otherwise nobody would notice. &lt;0.5 wink&gt;)</p>
<p>As always, comments and corrections are welcome. ^_^</p>
]]></content:encoded>
			<wfw:commentRss>http://4.flowsnake.org/archives/1035/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python vs Scheme: using files as both modules and programs</title>
		<link>http://4.flowsnake.org/archives/83</link>
		<comments>http://4.flowsnake.org/archives/83#comments</comments>
		<pubDate>Sun, 23 Mar 2008 02:49:03 +0000</pubDate>
		<dc:creator>Hans Nowak</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[Python vs Scheme]]></category>
		<category><![CDATA[scheme]]></category>

		<guid isPermaLink="false">http://4.flowsnake.org/archives/83</guid>
		<description><![CDATA[Python has a useful idiom, that allows one to use the same file as both a module and a program. Consider this simple example: # foo.py def bar(x): print "bar says:", x if __name__ == "__main__": bar(42) The if __name__ == &#8220;__main__&#8221; clause is only executed if foo.py is run as the &#8220;main program&#8221;. In [...]]]></description>
			<content:encoded><![CDATA[<p>Python has a useful idiom, that allows one to use the same file as both a module and a program. Consider this simple example:</p>
<pre># foo.py

def bar(x):
    print "bar says:", x

if __name__ == "__main__":

    bar(42)</pre>
<p>The <em>if __name__ == &#8220;__main__&#8221;</em> clause is only executed if <em>foo.py</em> is run as the &#8220;main program&#8221;. In other words, we can do both</p>
<pre>$ python foo.py
bar says: 42</pre>
<p>and</p>
<pre>$ python
Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; import foo
&gt;&gt;&gt; foo.bar(33)
bar says: 33</pre>
<p>Although admittedly a bit of a hack, this construct is well-known and often used.</p>
<p>Now, on to Chicken Scheme. Can we do the same? It required a bit of poking around in documentation and mailing list, but it appears the answer is yes.</p>
<pre>;; foo.scm

(define (foo x)
  (print "foo says: " x))

(define (main args)
  (print "args: " args)
  (foo 42))</pre>
<p>Now, we can run this as a script with <em>csi -ss</em> (which looks for a function called <em>main</em> and automagically calls it):</p>
<pre>$ csi -ss foo.scm
args: ()
foo says: 42</pre>
<p>Notice that the <em>main</em> function has an argument <em>args</em>, which contains the command line arguments passed to the program:</p>
<pre>$ csi -ss foo.scm 1 2 3
args: (1 2 3)
foo says: 42</pre>
<p>We can also import <em>foo.scm</em> from within an interactive session, in which cases <em>main</em> is not called:</p>
<pre>$ csi

CHICKEN
Version 3.0.0 - macosx-unix-gnu-x86     [ manyargs dload ptables applyhook ]
(c)2000-2008 Felix L. Winkelmann        compiled 2008-03-05 on niflheim.local (Darwin)

; loading /Users/zephyrfalcon/.csirc ...
; loading /usr/local/lib/chicken/3/readline.so ...
#;1&gt; (use foo)
; loading ./foo.scm ...
#;2&gt; (foo 101)
foo says: 101</pre>
<p>But, but! Isn&#8217;t Chicken primarily a compiler? Does the above work too when using <em>csc</em> rather than <em>csi</em>? Actually it does, but the invocation is  different. I use the following:</p>
<pre>$ csc foo.scm -postlude "(main (cdr (argv)))"

$ ./foo
args: ()
foo says: 42

$ ./foo 1 2 3
args: (1 2 3)
foo says: 42</pre>
<p>The <em>-postlude</em> option can be used to specify code that runs when the executable is called. (Actually, the <a href="http://chicken.wiki.br/Using%20the%20compiler#compiler-command-line-format">official explanation</a> is: &#8220;<em>Add</em> <tt>EXPRESSIONS</tt> <em>after all other toplevel expressions in the compiled file. This option may be given multiple times. Processing of this option takes place after processing of</em> <tt>-epilogue</tt>.&#8221;)</p>
<p>I use <em>(main (cdr (argv)))</em> as the postlude expression, which seems to pass command line arguments the same way as <em>csi -ss</em> passes them to the main function (although there might be a catch that I&#8217;m not aware of). The <em>cdr</em> is necessary because the first item of the list returned by <em>(argv)</em> is the name of the calling program (e.g. <em>&#8220;./foo&#8221;</em>).</p>
<p>(If there&#8217;s a better way, please let me know, as my knowledge about the compiler is limited.)</p>
<p>Next up: parsing command line arguments in both Python and Scheme&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://4.flowsnake.org/archives/83/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Python vs Scheme: function parameters (part III)</title>
		<link>http://4.flowsnake.org/archives/67</link>
		<comments>http://4.flowsnake.org/archives/67#comments</comments>
		<pubDate>Sat, 16 Feb 2008 13:57:04 +0000</pubDate>
		<dc:creator>Hans Nowak</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[Python vs Scheme]]></category>
		<category><![CDATA[scheme]]></category>

		<guid isPermaLink="false">http://4.flowsnake.org/archives/67</guid>
		<description><![CDATA[(Also see: part I, part II) Just discovered something neat. In Python, if a function has arguments that have a default value, then those defaults are bound when the function is defined. So the following function, when called with no arguments, always returns the same value: &#62;&#62;&#62; def f(x=random.randrange(0, 100)): return x ... &#62;&#62;&#62; f() [...]]]></description>
			<content:encoded><![CDATA[<p>(Also see: <a href="/archives/12">part I</a>, <a href="/archives/13">part II</a>)</p>
<p>Just discovered something neat. In Python, if a function has arguments that have a default value, then those defaults are bound when the function is defined. So the following function, when called with no arguments, always returns the same value:</p>
<pre>&gt;&gt;&gt; def f(x=random.randrange(0, 100)): return x
...
&gt;&gt;&gt; f()
32
&gt;&gt;&gt; f()
32
&gt;&gt;&gt; f()
32</pre>
<p>&#8230;because the default value for <em>x</em> is determined when <em>f</em> is defined, rather than when it&#8217;s called.</p>
<p>And this is not allowed at all:</p>
<pre>&gt;&gt;&gt; def z(a, b=a): print a, b
...
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
NameError: name 'a' is not defined</pre>
<p>I assumed that these rules would be the same in Chicken, but it turns out that this is not the case. This allows for some cool constructs that simply aren&#8217;t possible in Python. Like the example with the random number:</p>
<pre>&gt; (define (f #!optional (x (random 100))) x)
&gt; (f)
23
&gt; (f)
89
&gt; (f)
97</pre>
<p>It appears that <em>(random 100)</em> is computed whenever <em>f</em> is called, rather than when it&#8217;s defined. We can also refer to other arguments in this default expression:</p>
<pre>&gt; (define (g a #!optional (b (+ a 10)))
&gt;   (list a b))
&gt; (g 3)
(3 13)
&gt; (g 40)
(40 50)</pre>
<p>Good to know. This behavior is intentional rather than accidental, judging from the <a href="http://chicken.wiki.br/Extensions%20to%20the%20standard">Extensions to the standard</a> section in the user manual.</p>
]]></content:encoded>
			<wfw:commentRss>http://4.flowsnake.org/archives/67/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Python vs Scheme: strings</title>
		<link>http://4.flowsnake.org/archives/29</link>
		<comments>http://4.flowsnake.org/archives/29#comments</comments>
		<pubDate>Sun, 27 Jan 2008 03:55:18 +0000</pubDate>
		<dc:creator>Hans Nowak</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[Python vs Scheme]]></category>
		<category><![CDATA[scheme]]></category>

		<guid isPermaLink="false">http://4.flowsnake.org/archives/29</guid>
		<description><![CDATA[Python and Scheme have different philosophies when it comes to strings. Scheme strings are mutable and consist of characters, which are a separate type. By contrast, Python&#8217;s strings are immutable, and its &#8220;characters&#8221; are really strings with a length of one. Also, Python uses both &#8221; &#8221; and &#8216; &#8216; for string literals, while Scheme [...]]]></description>
			<content:encoded><![CDATA[<p>Python and Scheme have different philosophies when it comes to strings. Scheme strings are mutable and consist of characters, which are a separate type. By contrast, Python&#8217;s strings are immutable, and its &#8220;characters&#8221; are really strings with a length of one.</p>
<p>Also, Python uses both &#8221; &#8221; and &#8216; &#8216; for string literals, while Scheme only uses &#8221; &#8220;.</p>
<p>Aside from that, strings can be used in these languages in ways that are very similar (as opposed to e.g. C&#8217;s strings which tend to involve memory allocation and pointer arithmetic). So in this post, I will be focusing on common string operations, and what they look like in both Python and Scheme.</p>
<p>In Python, all these strings operations work out of the box. In Scheme, some are provided by R5RS, while others are found in <a href="http://srfi.schemers.org/srfi-13/srfi-13.html">SRFI-13</a> (a very useful library which has a large number of non-trivial string operations), and yet others are included by Chicken (but not necessarily part of other Scheme implementations). In the examples below, I&#8217;m assuming Chicken with SRFI-13 imported.</p>
<h4>Joining multiple strings »</h4>
<p>Python has the very obvious <em>+</em> operator to concatenate two strings, something which won&#8217;t work in Scheme; <em>(+ &#8220;a&#8221; &#8220;b&#8221;)</em> is an error. It also has the butt-ugly <em>str.join</em> method to join a list of strings. Scheme has <em>string-append</em> (R5RS) and <em>string-join</em> (SRFI-13).</p>
<pre># Python
&gt;&gt;&gt; "hello" + " " + "world"
'hello world'
&gt;&gt;&gt; " ".join(['my', 'name', 'is', 'poison'])
'my name is poison'

;; Scheme
&gt; (string-append "hello" " " "world")
"hello world"
&gt; (string-join '("my" "name" "is" "poison") " ")
"my name is poison"</pre>
<h4>Getting the length »</h4>
<p>These functions are very simple, but I&#8217;m mentioning them anyway because there might be surprises here for people coming from other languages. Python uses the <em>len()</em> function rather than a method (like e.g. Ruby and Io do). Scheme uses <em>string-length</em> rather than <em>length</em> (which only works on lists).</p>
<pre># Python
&gt;&gt;&gt; len("koyaanisqatsi")
13

;; Scheme
&gt; (string-length "koyaanisqatsi")
13</pre>
<h4>Substrings »</h4>
<p>Python uses the <em>[]</em> syntax for indexing and slicing; it also accepts negative numbers (to count from the end of the string). Scheme has <em>string-ref</em> and <em>substring</em>, which work similarly, except they don&#8217;t take negative values. (Note that <em>string-ref</em> returns a *character* rather than a one-length string.)</p>
<pre># Python
&gt;&gt;&gt; s = "hello"
&gt;&gt;&gt; s[0]
'h'
&gt;&gt;&gt; s[2]
'l'
&gt;&gt;&gt; s[1:3]
'el'
&gt;&gt;&gt; s[-3:]
'llo'

;; Scheme
&gt; (define s "hello")
&gt; (string-ref s 0)
#\h
&gt; (string-ref s 2)
#\l
&gt; (substring s 1 3)
"el"</pre>
<h4>Comparing strings »</h4>
<p>In Python, strings are compared with the usual <em>==</em> family of operators. Case matters; <em>&#8220;a&#8221;</em> does not compare equal to <em>&#8220;A&#8221;</em>. Scheme, on the other hand, has a number of functions to do the comparison; <em><a href="http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_idx_502">string=?</a></em> and friends for case-sensitive comparing like in Python, and the <em>string-ci=?</em> family for case-insensitive comparing.</p>
<pre># Python
&gt;&gt;&gt; "abc" == "abc"
True
&gt;&gt;&gt; "abc" == "ABC"
False
&gt;&gt;&gt; "b" &gt; "a"
True

;; Scheme
&gt; (string=? "abc" "ABC")
#f
&gt; (string-ci=? "abc" "ABC")
#t
&gt; (string&gt;? "b" "a")
#t</pre>
<p>SRFI-13 also provides equivalents for Python&#8217;s useful <em>startswith()</em> and <em>endswith()</em> methods:</p>
<pre>&gt; (string-prefix? "He" "Herbert")
#t
&gt; (string-suffix? "tt" "Abbott")
#t</pre>
<h4>Changing case »</h4>
<p>Speaks for itself. Note that R5RS defines <em>char-upcase</em> and <em>char-downcase</em>, but not <em>string-upcase</em> or <em>string-downcase</em> (those are in SRFI-13).</p>
<pre>&gt;&gt;&gt; "kibbles and bits".upper()
'KIBBLES AND BITS'
&gt;&gt;&gt; "KIBBLES AND BITS".lower()
'kibbles and bits'
&gt;&gt;&gt; "kibbles and bits".capitalize()
'Kibbles and bits'
&gt;&gt;&gt; "kibbles and bits".title()
'Kibbles And Bits'

;; Scheme
&gt; (string-upcase "kibbles and bits")
"KIBBLES AND BITS"
&gt; (string-downcase "KIBBLES AND BITS")
"kibbles and bits"
&gt; (string-titlecase "kibbles and bits")
"Kibbles And Bits"</pre>
<h4>Splitting »</h4>
<p>Splitting a string into a list of smaller strings is a common thing to do in high-level languages. Luckily, for common cases, we don&#8217;t have to resort to regular expressions. Python uses the <em>split()</em> method, Scheme has <em>string-tokenize</em> (SRFI-13) and <em>string-split</em> (Chicken).</p>
<pre># Python
&gt;&gt;&gt; "a few good men".split()
['a', 'few', 'good', 'men']
&gt;&gt;&gt; "abracadabra".split("b")
['a', 'racada', 'ra']

;; Scheme
&gt; (string-tokenize "a few good men")  ;; SRFI-13
("a" "few" "good" "men")
&gt; (string-split "a few good men")     ;; Chicken built-in
("a" "few" "good" "men")
&gt; (string-split "abracadabra" "b")
("a" "racada" "ra")</pre>
<h4>Trimming »</h4>
<p>To trim characters from the left and/or right side of a string, Python uses the <em>lstrip</em> (from the left), <em>rstrip</em> (from the right) or <em>strip</em> (both sides) methods. Somewhat asymmetrically, in Scheme (or, more precisely, SRFI-13) these functions are called <em>string-trim </em>(from the left), <em>string-trim-right</em> (from the right) and <em>string-trim-both</em> (both sides).</p>
<p>Both Python and Scheme allow you to specify the character(s) that need to be stripped. By default, whitespace is removed, as this seems to be the most common use case.</p>
<pre># Python
&gt;&gt;&gt; s = "  i like cookies  "
&gt;&gt;&gt; s.strip()
'i like cookies'
&gt;&gt;&gt; s.lstrip()
'i like cookies  '
&gt;&gt;&gt; s.rstrip()
'  i like cookies'
&gt;&gt;&gt; "xxxhi!xxx".strip("x")
'hi!'

;; Scheme
&gt; (define s "  i like cookies  ")
&gt; (string-trim s)
"i like cookies  "
&gt; (string-trim-right s)
"  i like cookies"
&gt; (string-trim-both s)
"i like cookies"
&gt; (string-trim-both "xxxhi!xxx" #\x)
"hi!"</pre>
<h4>Looping »</h4>
<p>In Python, you can loop over a string (using <em>for</em>) or turn it into a list, but what you get is essentially a list of strings with length one. In Scheme, you get characters. Use <em>string-&gt;list</em> to get a list of characters, and <a href="http://srfi.schemers.org/srfi-13/srfi-13.html#string-map"><em>string-map</em></a> to map one string to another (much like the regular <em>map</em>, but it takes and returns a string).</p>
<pre># Python
&gt;&gt;&gt; for c in "hello": print c,
...
h e l l o
&gt;&gt;&gt; list("hello")
['h', 'e', 'l', 'l', 'o']

;; Scheme
&gt; (string-&gt;list "hello")
(#\h #\e #\l #\l #\o)
&gt; (for-each
&gt;   (lambda (c) (printf "~a! " c))
&gt;   (string-&gt;list "hello"))
h! e! l! l! o!
&gt; (string-map char-upcase "hello")
"HELLO"</pre>
<h4>Searching »</h4>
<p>Python has several ways to search strings for contents&#8230; like the <em>find</em>/<em>rfind</em> methods (and their <em>index</em>/<em>rindex</em> counterparts) to find the index of a matching substring, and the <em>in</em> operator if you just want to know if a string has a certain substring, but don&#8217;t need to know where exactly it starts.</p>
<p>You can do the same things in Scheme, assuming you use SRFI-13, as R5RS does not define any of this. <em>string-index</em> searches for a character (or a character set or a predicate), <em>string-contains</em> searches for a substring. When found, it returns the index, otherwise <em>#f</em> (which is useful because it allows one to write <em>(if (string-contains s1 s2) &#8230;))</em>.</p>
<pre># Python
&gt;&gt;&gt; "lemon-flavored jellibeans".find("e")
1
&gt;&gt;&gt; "lemon-flavored jellibeans".rfind("e")
21
&gt;&gt;&gt; "lemon-flavored jellibeans".find("el")
16
&gt;&gt;&gt; "lemon-flavored jellibeans".find("xyz")
-1
&gt;&gt;&gt; "el" in "lemon-flavored jellibeans"
True

;; Scheme
&gt; (string-index "lemon-flavored jellibeans" #\e)
1
&gt; (string-index-right "lemon-flavored jellibeans" #\e)
21
&gt; (string-contains "lemon-flavored jellibeans" "el")
16
&gt; (string-contains "lemon-flavored jellibeans" "xyz")
#f</pre>
<h4>Replacing »</h4>
<p>Python&#8217;s <em>replace()</em> method is very easy: simply specify the substring that needs to be replaced, and its replacement. By contrast, SRFI-13&#8242;s <a href="http://srfi.schemers.org/srfi-13/srfi-13.html#string-replace"><em>string-replace</em></a> is more sophisticated.  It takes a string, a replacement string, and start/end indices that indicate what part of the string needs replaced. See the example below.</p>
<pre># Python
&gt;&gt;&gt; "I like cookies".replace("cookie", "hot dog")
'I like hot dogs'

;; Scheme
&gt; (string-replace "i like cookies" "hot dog" 7 13)
"i like hot dogs"</pre>
<p>I don&#8217;t know if there&#8217;s a version that is easier to use floating around somewhere (in a SRFI or otherwise), but it&#8217;s not so hard to write something that emulates the Python behavior:</p>
<pre>(define (string-replace-v2 s before after)
  (let ((idx (string-contains s before)))
    (if idx
        (string-replace s after idx (+ idx (string-length before)))
        s)))</pre>
<p>Also, Chicken has <a href="http://chicken.wiki.br/Unit%20extras#string-translate*"><em>string-translate*</em></a>, which works for our purposes, but is used with a table of elements to be replaced:</p>
<pre>&gt; (string-translate* "i like cookies"
&gt;   '(("cookie" . "hot dog")))
"i like hot dogs"</pre>
<p align="left">:::</p>
<p>This has become a long post, longer than I intended, and there are still many things I haven&#8217;t even touched upon yet&#8230; like Unicode, or the fact that some of the aforementioned functions have equivalents that change the string in-place, rather than returning a new string. Anyway, this wasn&#8217;t meant to be a complete reference; it&#8217;s more of a starting point, or a quick way to look up &#8220;I can do X in Python, how do I do it in Scheme?&#8221;</p>
<p>Further reading:</p>
<ul>
<li><a href="http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.3.5">Strings in R5RS</a></li>
<li><a href="http://srfi.schemers.org/srfi-13/srfi-13.html">SRFI-13: String libraries</a></li>
<li>Chicken Scheme: <a href="http://chicken.wiki.br/Unit%20extras#strings">additional string functions</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://4.flowsnake.org/archives/29/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Python vs Scheme: dictionaries</title>
		<link>http://4.flowsnake.org/archives/36</link>
		<comments>http://4.flowsnake.org/archives/36#comments</comments>
		<pubDate>Thu, 17 Jan 2008 18:42:22 +0000</pubDate>
		<dc:creator>Hans Nowak</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[Python vs Scheme]]></category>
		<category><![CDATA[scheme]]></category>

		<guid isPermaLink="false">http://4.flowsnake.org/archives/36</guid>
		<description><![CDATA[Python has a separate dictionary type. I&#8217;m assuming most of my readers are familiar with it, as it&#8217;s very common; if not, please read the fine tutorial first, followed by the library reference. In short, Python&#8217;s dictionaries are mutable objects that associate unique keys with values. There is special syntax to create them. Now, going [...]]]></description>
			<content:encoded><![CDATA[<p>Python has a separate dictionary type. I&#8217;m assuming most of my readers are familiar with it, as it&#8217;s very common; if not, please read the fine <a href="http://docs.python.org/tut/node7.html#SECTION007500000000000000000">tutorial</a> first, followed by the <a href="http://docs.python.org/lib/typesmapping.html">library reference</a>.</p>
<p>In short, Python&#8217;s dictionaries are mutable objects that associate unique keys with values. There is special syntax to create them.</p>
<p>Now, going by R5RS, Scheme doesn&#8217;t even have anything similar. All it has is three closely related functions, that look up pairs in a list, based on a &#8220;key&#8221; which is matched to the first element of each pair. These functions are <em>assq</em>, <em>assv</em> and <em>assoc</em>. (See <a href="http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_idx_434">here</a> in R5RS.)</p>
<p>Naturally, it&#8217;s possible to write extensions in Scheme that look more like Python&#8217;s dict (or Ruby&#8217;s Hash, etc), and I&#8217;m sure people have done so; for example, <a href="http://srfi.schemers.org/srfi-69/srfi-69.html">SRFI-69</a> defines hash tables. But for now, let&#8217;s see what we can do with the bare-bones approach.</p>
<p>Its usage is simple: you define a list of pairs, possibly augmenting them by consing new pairs onto it, or deleting elements from it. (The order doesn&#8217;t really matter.) Then you use the aforementioned functions to look up &#8220;keys&#8221; (matched to the first element in each pair). If not found, <em>#f</em> is returned, otherwise the matching pair.</p>
<p>That&#8217;s right; the whole pair is returned, not just the second element of the pair. By doing so, Scheme sidesteps the problem that some languages have (e.g. Ruby); it either returns a pair (found) or <em>#f</em> (not found), so there can never be any confusion whether the key was found or not. By contrast, in Ruby, if <em>myhash[value]</em> returns <em>nil</em>, that could mean that the value was found and that its associated value was <em>nil</em>, *or* that it was not found at all. (Python doesn&#8217;t have this problem either; it raises a <em>KeyError</em> exception if the key is not found; in addition, the Ruby behavior can be emulated with the <em>dict.get()</em> method.)</p>
<p>Anyway, here&#8217;s an example (R5RS only but we&#8217;re secretly assuming that <em>filter</em> exists):</p>
<pre>(define language-designers
  '((guido python)
    (matz ruby)
    (rasmus php)
    (larry perl)))

; add some...
(define language-designers
  (cons '(felix chicken) language-designers))

; I don't like PHP; remove it :-)
(define language-designers
  (filter (lambda (pair) (not (equal? (cadr pair) 'php)))
          language-designers))

(print (assoc 'guido language-designers))  ; =&gt; (guido python)
(print (assoc 'hans language-designers))   ; =&gt; #f</pre>
<p>Note how the usage is completely different from Python&#8217;s dicts. This can be written differently &#8212; hell, OF COURSE it can be written differently, it&#8217;s Scheme! :-) But let&#8217;s stick with this approach for a minute.</p>
<p>(I&#8217;m using <em>assoc</em> here, which compares key and first element using the <em>equal?</em> predicate. <em>assq</em> and <em>assv</em> basically do the same thing, using the <em>eq?</em> and <em>eqv?</em> predicates, respectively. <a href="http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.1">Equality testing</a> in Scheme will be dealt with in yet another forthcoming post&#8230;)</p>
<p>Basically, this is all you need. Since a &#8220;dictionary&#8221; is just a list of pairs, all the usual list operators apply, and can be used to write any Python-esque dict operations fairly easily: <em>keys</em>, <em>has_key</em>, adding and removing using <em>[]</em>, etc. (Doing so is left as an exercise for the reader. ;-)</p>
<p>Fortunately, the author of <a href="http://srfi.schemers.org/srfi-1/srfi-1.html">SRFI-1</a> (a list library) recognized the need for such functions, and supplied a few of them. Using the SRFI, we could write:</p>
<pre>(define language-designers
  (alist-cons 'felix chicken language-designers))

(define language-designers
  (alist-delete 'rasmus language-designers))</pre>
<p>&#8230; which is at least a bit clearer.</p>
<p>(More about Scheme lists, and SRFI-1 which is *very* necessary, in a separate post.)</p>
]]></content:encoded>
			<wfw:commentRss>http://4.flowsnake.org/archives/36/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Python vs Scheme: Simple list comprehensions</title>
		<link>http://4.flowsnake.org/archives/21</link>
		<comments>http://4.flowsnake.org/archives/21#comments</comments>
		<pubDate>Wed, 09 Jan 2008 01:19:09 +0000</pubDate>
		<dc:creator>Hans Nowak</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[chicken]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[Python vs Scheme]]></category>
		<category><![CDATA[scheme]]></category>

		<guid isPermaLink="false">http://4.flowsnake.org/archives/21</guid>
		<description><![CDATA[Python has a nifty feature called list comprehensions. Originally borrowed from Haskell, this is a (mostly) compact way to generate lists, without having to resort to the map and filter functions (which are often considered less clear and tend to rely on Python&#8217;s underpowered lambda). Scheme, being a functional language, has an entirely different attitude [...]]]></description>
			<content:encoded><![CDATA[<p>Python has a nifty feature called <a href="http://docs.python.org/tut/node7.html#SECTION007140000000000000000">list comprehensions</a>. Originally borrowed from Haskell, this is a (mostly) compact way to generate lists, without having to resort to the <em>map</em> and <em>filter</em> functions (which are often considered less clear and tend to rely on Python&#8217;s underpowered <em>lambda</em>).</p>
<p>Scheme, being a functional language, has an entirely different attitude toward <em>map</em>, <em>filter</em> and friends. Their use is encouraged, rather than being downplayed. In spite of that, there are situations where list comprehensions (or some form thereof) would be useful. So, <a href="http://srfi.schemers.org/srfi-42/srfi-42.html">SRFI-42</a> introduces &#8220;eager comprehensions&#8221;.</p>
<p>Rather than providing one construct, SRFI-42 has a number of forms, some of which seem to exist for efficiency reasons. For now, I&#8217;m just going to look at <em>list-ec</em>, which (in its most basic form) is a close cousin of Python&#8217;s list comprehensions.</p>
<p>Let&#8217;s run a simple example in Chicken:</p>
<pre>&gt; (use syntax-case)
; loading /usr/local/lib/chicken/3/syntax-case.so ...
; loading /usr/local/lib/chicken/3/syntax-case-chicken-macros.scm ...
&gt; (use srfi-42)
; loading /usr/local/lib/chicken/3/srfi-42.scm ...
; loading /usr/local/lib/chicken/3/srfi-42-support.so ...

&gt; (list-ec (: i 5) (* i i))
(0 1 4 9 16)</pre>
<p>(Note: <a href="http://www.call-with-current-continuation.org/eggs/srfi-42.html"><em>srfi-42</em></a> is an egg that needs to be installed first. It depends on another egg, <a href="http://www.call-with-current-continuation.org/eggs/syntax-case.html"><em>syntax-case</em></a>. Make sure these are installed, and imported in the correct order, or the examples won&#8217;t work!)</p>
<p>In Python, this would look like:</p>
<pre>&gt;&gt;&gt; [i*i for i in range(5)]
[0, 1, 4, 9, 16]</pre>
<p>In this case, we could easily write this with a <em>map</em>&#8230; if Scheme had something similar to Python&#8217;s <em>range</em> function, which it doesn&#8217;t. In fact, the lack of such a construct seems to have been a major motivation for writing SRFI-42. The author states:</p>
<blockquote><p>&#8220;The origin of this SRFI is my frustration that there is no simple [form] for the list of integers from 0 to <em>n</em>-1. With this SRFI it is <code>(list-ec (: i n) i)</code>.&#8221;</p></blockquote>
<p>Moreover, much like in Python, eager comprehensions are capable of more powerful expressions, that are not so easily written using <em>map</em>. Like this one, which isn&#8217;t terribly complex:</p>
<pre>&gt; (list-ec (: n 1 4) (: i n) (list n i))
((1 0) (2 0) (2 1) (3 0) (3 1) (3 2))

# Python:
&gt;&gt;&gt; [(n,i) for n in range(1, 4) for i in range(n)]
[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)]</pre>
<p>Much, much more is possible using SRFI-42, most of which I don&#8217;t understand yet :-), so for now I&#8217;m sticking to these simple examples. There will probably be a part II to this post, at some point. However, as a teaser, here&#8217;s a way to write Python&#8217;s <em>enumerate</em> (that works on strings and lists and probably some other types):</p>
<pre>&gt; (define (enumerate seq)
&gt;   (list-ec (: x (index i) seq) (list i x)))

&gt; (enumerate "hello")
((0 #\h) (1 #\e) (2 #\l) (3 #\l) (4 #\o))
&gt; (enumerate '(guido larry matz))
((0 guido) (1 larry) (2 matz))</pre>
]]></content:encoded>
			<wfw:commentRss>http://4.flowsnake.org/archives/21/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Python vs Scheme: Formatted output</title>
		<link>http://4.flowsnake.org/archives/16</link>
		<comments>http://4.flowsnake.org/archives/16#comments</comments>
		<pubDate>Fri, 04 Jan 2008 15:45:05 +0000</pubDate>
		<dc:creator>Hans Nowak</dc:creator>
				<category><![CDATA[Python vs Scheme]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[scheme]]></category>

		<guid isPermaLink="false">http://4.flowsnake.org/archives/16</guid>
		<description><![CDATA[In Python, it&#8217;s common to format string output using the % operator. (There are other ways, but this is the oldest and most widely used.) A few examples of frequently used string substitutions: # integer &#62;&#62;&#62; "I ate %d hamburgers" % (4,) 'I ate 4 hamburgers' # string &#62;&#62;&#62; "Hello, my name is %s" % [...]]]></description>
			<content:encoded><![CDATA[<p>In Python, it&#8217;s common to format string output using the <em>%</em> operator. (There are <a href="http://www.python.org/doc/2.4/whatsnew/node5.html">other ways</a>, but this is the oldest and most widely used.) A few examples of frequently used string substitutions:</p>
<pre># integer
&gt;&gt;&gt; "I ate %d hamburgers" % (4,)
'I ate 4 hamburgers'

# string
&gt;&gt;&gt; "Hello, my name is %s" % ("John Doe",)
'Hello, my name is John Doe'

# float rounded to 2 decimals
&gt;&gt;&gt; "Execution took %0.2f seconds" % (12.5678,)
'Execution took 12.57 seconds'

# compound objects
&gt;&gt;&gt; "Output: %s" % (locals().keys(),)
"Output: ['__builtins__', '__name__', '__doc__']"

# repr
&gt;&gt;&gt; "Invalid argument: %r" % ("foobar",)
"Invalid argument: 'foobar'"

# multiple values
&gt;&gt;&gt; "Brought to you by the letters %s, %s and %s" % ("P", "Q", "R")
'Brought to you by the letters P, Q and R'</pre>
<p>Now, on to Scheme. As far as I can tell, R5RS has nothing of the sort. Which is somewhat surprising, or then again maybe not, when you realize that it&#8217;s not so difficult to write a formatting function that works for most cases.</p>
<p>Which is exactly what Chicken provides, in the <a href="http://chicken.wiki.br/Unit%20extras#formatted-output">extras</a> unit. The <em>printf</em>, <em>sprintf</em>, <em>fprintf</em> and <em>format</em> functions all take a format string and a number of arguments (so no messing with tuples like Python does &#8212; although that is a consequence of using an operator rather than a function).</p>
<p>While <em>printf</em> and friends are underpowered, they work for most cases:</p>
<pre>&gt; (printf "Once again, I ate ~a hamburgers.~n" 4)
Once again, I ate 4 hamburgers.

&gt; (printf "I saw ~a at the ~a ~a, having ~a ~as.~n"
     "Fred" 'foo 'bar '17 'martini)
I saw Fred at the foo bar, having 17 martinis.</pre>
<p>From what I&#8217;ve seen, the <em>~a</em> and <em>~n</em> directives are the most common; there are a few more, like <em>~x</em> to display a number as hexadecimal, and <em>~\n</em> to skip all whitespace in the string until the next non-format character. (Note that this actually *extends* <a href="http://srfi.schemers.org/srfi-28/srfi-28.html">SRFI-28</a>, which describes a form of string formatting that is rather bare-bones.)</p>
<p>As said, this works for most cases, but not when you, for example, want to display a float with 2 decimals. <em>printf</em> has no equivalent for Python&#8217;s &#8220;%0.2f&#8221;.</p>
<p>Fortunately, there are extensions that do allow this. The <a href="http://www.call-with-current-continuation.org/eggs/format.html"><em>format</em></a> egg, for instance, provides Common Lisp-like format strings.</p>
<p>Installing the egg is easy, more about which in a separate post; for now, suffice to say that</p>
<pre>$ sudo chicken-setup format</pre>
<p>should probably do the trick. Then, use the egg:</p>
<pre>&gt; (use format)
; loading /usr/local/lib/chicken/3/format.so ...

&gt; (format #f "The pie was ~,2F cm thick.~%" 3.1415)
"The pie was 3.14 cm thick.\n"</pre>
<p>(It provides a function <em>format</em> that, when imported, overrides the built-in <em>format</em> function. <em>printf</em> and friends are not affected, though.)</p>
<p>More information about the directives can be found in the documentation of the <a href="http://www.call-with-current-continuation.org/eggs/format.html">format</a> egg, but basically they work the same way as the directives found in <em>printf</em> &amp; co. There&#8217;s just more of them, with more options.</p>
]]></content:encoded>
			<wfw:commentRss>http://4.flowsnake.org/archives/16/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python vs Scheme: function parameters (part II)</title>
		<link>http://4.flowsnake.org/archives/13</link>
		<comments>http://4.flowsnake.org/archives/13#comments</comments>
		<pubDate>Wed, 02 Jan 2008 14:00:08 +0000</pubDate>
		<dc:creator>Hans Nowak</dc:creator>
				<category><![CDATA[Python vs Scheme]]></category>
		<category><![CDATA[chicken]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[scheme]]></category>

		<guid isPermaLink="false">http://4.flowsnake.org/archives/13</guid>
		<description><![CDATA[In part I, I looked at the handling of function arguments as specified in R5RS. Chicken adds three more ways to handle special arguments, using the keywords #!optional, #!rest and #!key. (Here&#8217;s the relevant page in the Chicken documentation.) The way I understand it, #!rest is just another way to collect optional arguments in a [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="/archives/12">part I</a>, I looked at the handling of function arguments as specified in R5RS. Chicken adds three more ways to handle special arguments, using the keywords <em>#!optional</em>, <em>#!rest</em> and <em>#!key</em>. (Here&#8217;s the relevant <a href="http://chicken.wiki.br/Extensions%20to%20the%20standard">page</a> in the Chicken documentation.)</p>
<p>The way I understand it, <em>#!rest</em> is just another way to collect optional arguments in a list. For our purposes, the following code is equivalent to <em>(f a b . args)</em>:</p>
<pre>&gt; (define (r a b #!rest args)
     (list a b args))
&gt; (r 1 2)
(1 2 ())
&gt; (r 1 2 3)
(1 2 (3))</pre>
<p>Optional arguments can also be specified separately (rather than collecting them all in a list). For this, use the <em>#!optional</em> keyword, followed by a list of names. Arguments passed to the function are associated with these names based on position. If not specified, the name defaults to <em>#f</em>.</p>
<pre>&gt; (define (o a #!optional b c)
     (list a b c))
&gt; (o 1)
(1 #f #f)
&gt; (o 2 'fred)
(2 fred #f)

;; roughly equivalent to Python:
;; def o(a, b=None, c=None): ...</pre>
<p>We can also specify defaults:</p>
<pre>&gt; (define (p #!optional (a 42) (b 'cookie))
     (list a b))
&gt; (p)
(42 cookie)
&gt; (p 103)
(103 cookie)

;; roughly equivalent to Python:
;; def p(a=42, b="cookie"): ...</pre>
<p>Again, values are associated with names based on position.</p>
<p>It would be useful if we could specify a parameter&#8217;s name. What if, in the above example, we want to override <em>b</em> but not <em>a</em>? In that case, we need to use <em>#!key</em>. This works much like <em>#!optional</em>, except that we can specify names (using <em>#:name </em>syntax). In fact, we *must* specify names, because positional arguments are ignored (unless we also specify <em>#!optional</em> or <em>#!rest</em>).</p>
<pre>&gt; (define (k #!key (a 42) (b 'cookie))
        (list a b))
&gt; (k)
(42 cookie)
&gt; (k 1)
(42 cookie)  ;; neither a nor b is 1
&gt; (k #:b 'possum)
(42 possum)
&gt; (k #:b 'possum #:a 99) ; order of args doesn't matter
(99 possum)
&gt; (k b: 'possum) ; this is also allowed
(42 possum)</pre>
<p>So, in order to set a value for <em>a</em>, we must use <em>#a: value</em> in the function call. <em>value:</em> is also allowed.</p>
<p>Note if a function specifies both <em>#!key</em> and <em>#!rest</em>, keyword arguments passed to the function will show up in the rest argument as well, no matter whether there&#8217;s a matching name in <em>#!key</em> or not.</p>
<pre>&gt; (define (z #!rest rest #!key (a 42) (b 'cookie))
     (list a b rest))
&gt; (z)
(42 cookie ())
&gt; (z 1 2)
(42 cookie (1 2))
&gt; (z #:b 'soup 52)
(42 soup (b: soup 52))
&gt; (z #:a 10 #:q 129)
(10 cookie (a: 10 q: 129))</pre>
<p>In fact, using just <em>#!rest</em>, we can emulate Python&#8217;s <em>**kwargs</em> construct (sort of):</p>
<pre>&gt; (define (y #!rest r) r)
&gt; (y #:a 3)
(a: 3)
&gt; (y 1 2 3 #:foo 'bar)
(1 2 3 foo: bar)</pre>
<p>(&#8220;Parsing&#8221; this list of rest args requires a bit of special code to collect the pairs; at this point, I&#8217;m not sure if Chicken provides such a function out of the box.)</p>
<p>By the way, we can pass the resulting list to <em>apply</em> without problems:</p>
<pre>&gt; (apply y '(1 2 3))
(1 2 3)
&gt; (apply y '(1 2 3 foo: bar))
(1 2 3 foo: bar)
&gt; (apply y '(1 2 3 #:foo bar))
(1 2 3 foo: bar)</pre>
<p>What I like about the Chicken construct is that it doesn&#8217;t mix up positional and keyword arguments (unlike Python, although there&#8217;s a <a href="http://www.python.org/dev/peps/pep-3102/" title="PEP 3102">PEP</a> to fix this in Python 3000).</p>
<p>Anyway, while all this is powerful, it&#8217;s probably generally a good idea not to make argument lists too complicated. (The same is true in Python, by the way.)</p>
]]></content:encoded>
			<wfw:commentRss>http://4.flowsnake.org/archives/13/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python vs Scheme: function parameters (part I)</title>
		<link>http://4.flowsnake.org/archives/12</link>
		<comments>http://4.flowsnake.org/archives/12#comments</comments>
		<pubDate>Tue, 01 Jan 2008 23:36:52 +0000</pubDate>
		<dc:creator>Hans Nowak</dc:creator>
				<category><![CDATA[Python vs Scheme]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[scheme]]></category>

		<guid isPermaLink="false">http://4.flowsnake.org/archives/12</guid>
		<description><![CDATA[Python supports various ways to handle arguments passed to functions: # regular def f(a, b, c): ... # default arguments def f(a, b=3, c=100): ... # any number of positional parameters def f(x, *args): ... # any number of keyword arguments def f(y, **kwargs): ... # or a mixture! def f(self, *args, **kwargs): ... Scheme [...]]]></description>
			<content:encoded><![CDATA[<p>Python supports various ways to handle arguments passed to functions:</p>
<pre># regular
def f(a, b, c): ...

# default arguments
def f(a, b=3, c=100): ...

# any number of positional parameters
def f(x, *args): ...

# any number of keyword arguments
def f(y, **kwargs): ...

# or a mixture!
def f(self, *args, **kwargs): ...</pre>
<p>Scheme supports a few similar forms, and what it doesn&#8217;t have is complemented by Chicken. Let&#8217;s have a look.</p>
<p>The &#8220;regular&#8221; argument list looks like this:</p>
<pre>&gt; (define (f a b c)
     (list a b c))
&gt; (f 1 2 3)
(1 2 3)
&gt; (f 3 4)
...error: not enough arguments...

;; (Python) def f(a, b, c): ...</pre>
<p><em>f</em> takes three arguments, no more, no less.</p>
<pre>&gt; (define (g a b . rest)
     (list a b rest))
&gt; (g 1 2)
(1 2 ())
&gt; (g 1 2 3)
(1 2 (3))
&gt; (g 1 2 3 4 5 6 7)
(1 2 (3 4 5 6 7))

;; (Python) def g(a, b, *rest): ...</pre>
<p><em> g</em> takes two mandatory arguments, and any number of optional arguments, which are stored in the list <em>rest</em>. So, we can call <em>(g 1 2)</em> in which case <em>rest</em> is empty, but we can also call it as <em>(g 1 2 3 4)</em> which gives rest the value <em>(3 4)</em>.</p>
<p>If we want a function that takes any number of arguments, with no mandatory ones, we use the following:</p>
<pre>&gt; (define (h . args) (list args))
&gt; (h)
(())
&gt; (h 1 2 3)
((1 2 3))

;; (Python) def h(*args): ...</pre>
<p>Note, however, that this doesn&#8217;t work for a <em>lambda</em> (because <em>(lambda (. args))</em> is not valid syntax). In that case, use <em>args</em> rather than an argument list:</p>
<pre>&gt; (define i (lambda args (list args)))
&gt; (i)
(())
&gt; (i 1 2 3)
((1 2 3))</pre>
<p>This is all the argument handling that Scheme has to offer (in R5RS; read more about it <a href="http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-7.html#%_idx_96">here</a>). Chicken has several extensions to this standard, more about which tomorrow.</p>
]]></content:encoded>
			<wfw:commentRss>http://4.flowsnake.org/archives/12/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

