Being on sabbatical has given me a bit of experience with other systems and languages. Also, my kids are now old enough to “mess around” with programming. Learning from both of these, I’d like to hazard a bit of HtDP heresy: students should learn for i = 1 to 10 before they learn
To many of you, this may seem obvious. I’m not writing to you. Or maybe you folks can just read along and nod sagely.
HtDP takes this small and very lovely thing—recursive traversals over inductively defined data—and shows how it covers a huge piece of real estate. Really, if students could just understand how to write this class of programs effectively, they would have a vastly easier time with much of the rest of their programming careers, to say nothing of the remainder of their undergraduate tenure. Throw a few twists in there—a bit of mutation for efficiency, some memoization, some dynamic programming—and you’re pretty much done with the programming part of your first four years.
The sad thing is that many, many students make it through an entire four-year curriculum without ever really figuring out how to write a simple recursive traversal of an inductively defined data structure. This makes professors sad.
Among the Very Simple applications of this nice idea is that of “indexes.” That is, the natural numbers can be regarded as an inductively defined set, where a natural number is either 0 or the successor of a natural number. This allows you to regard any kind of indexing loop as simply a special case of … a recursive traversal of an inductively defined data structure.
So here’s the problem: in September, you face a bunch of bright-eyed, enthusiastic, deeply forgiving first-year college students. And you give them the recursive traversal of the inductively defined data structure. A very small number of them get it, and they’re off to the races. The rest of them struggle, and struggle, and finally get their teammates to help them write the code, and really wish they’d taken some other class.
NB: the rest of this makes less sense… even to me. Not finished.
The notion of repeated action is a visceral and easily-understood one. Here’s what I mean. “A human can multiply a pair of 32-bit integers in about a minute. A computer can multiply 32-bit integers at a rate of several billion per second, or about a hundred billion times as fast as a person.” That’s an easily-understood claim: we understand what it means to the same thing a whole bunch of times really fast.
So, when I write
for i=[1..100] multiply_two_numbers();
It’s pretty easy to understand that I’m doing something one hundred times.
To be honest, though, I’m probably flattering myself if I think that this blog post is being read by anyone who doesn’t already know lots about Rust.
One of the key requirements of a language like Rust is that it be embeddable; that is, it should be possible to call Rust code from another language just as it’s possible to call C code from another language.
This is now possible.
To illustrate this, Brian Anderson posted a lovely example of embedding Rust in Ruby. But of course, embedding Rust in Ruby is pretty much exactly the same as embedding Rust in any other language.
So, without further ado, here’s the setup. You just happen to have a small web app written in Racket that performs a Gaussian Blur. You decide to optimize the performance by porting your code to Rust. Then you want to plug your Rust code into your Racket application. Done! Here’s the github repo that contains all of the code.
Let’s see that again in slow motion.
First, here’s the gaussian blur function, written in Racket. We’re going to stick with a grayscale image. It works fine in color, but the code is just that much harder to read.
;; the gaussian filter used in the racket blur.;; boosted center value by 1/1000 to make sure that whites stay white.(definefilter'[[0.0110.0840.011][0.0840.6200.084][0.0110.0840.011]]);; racket-blur: blur the image using the gaussian filter;; number number list-of-bytes -> vector-of-bytes(define(racket-blurwidthheightdata)(definedata-vec(list->vectordata));; ij->offset : compute the offset of the pixel data within the buffer(define(ij->offsetij)(+i(*jwidth)))(definebytes-len(*widthheight))(definenew-bytes(make-vectorbytes-len0))(definefilter-x(length(carfilter)))(definefilter-y(lengthfilter))(defineoffset-x(/(sub1filter-x)2))(defineoffset-y(/(sub1filter-y)2));; compute the filtered byte array(for*([xwidth][yheight])(definenew-val(for*/fold([sum0.0])([dxfilter-x][dyfilter-y])(definesample-x(modulo(+dx(-xoffset-x))width))(definesample-y(modulo(+dy(-yoffset-y))height))(definesample-value(vector-refdata-vec(ij->offsetsample-xsample-y)))(defineweight(list-ref(list-reffilterdy)dx))(+sum(*weightsample-value))))(vector-set!new-bytes(ij->offsetxy)new-val))(vector->listnew-bytes))
Suppose we want to rewrite that in Rust. Here’s what it might look like:
Pretty similar. Of course, it uses curly braces, so it runs about three times faster…
So: what kind of glue code is necessary to link the Rust code to the Racket code? Not a lot. On the Rust side, we need to create a pointer to the C data, then copy the result back into the source buffer when we’re done with the blur:
The first Winnecowetts olympics is come and gone, and calling anything the “first” is really just asking for trouble, so I guess I’m just being optimistic.
Anyhow, it was a great success. We had 8 participants, and four events.
Target shooting
Shoot a nerf dart through a hanging bicycle tire. Three attempts at each distance.
Gold : Christopher Moulton & Alex Clements
Silver : Xavier Clements
Olympic Hide & Seek
Gold : Alex Clements, Ben Taylor, Xavier Clements
Silver : Christopher Moulton, Nathan Clements
Tower Building
Build a tower out of Kapla blocks. Each team had the same number of blocks. I think it was about 40.
Gold : Alex Clements
Silver : Ben Taylor & Nathan Clements
Bronze :
Pool Noodle Javelin
Throw a pool noodle as far as possible.
Gold : Nathan Clements
Silver : Alex Clements
Bronze : Alton Coolidge
Egg Roll (self)
Lying on back and grasping knees to chest, roll along from start line to finish line (about 20m).
As I write this, it’s Monday, August 6th. Charlotte Clews is organizing this year, and it appears that there will be two events that include the swim; the Maine Mountain Challenge, and the Granite Mon. Yesterday was the first swim. Here’s the picture:
2012 Swimmers
From left, the swimmers:
Charlotte Clews,
Jerome Lawther,
Justin Pollard,
John Clements,
Mary Clews,
first-time-swimmer Pat Starkey, and
Moira McMahon
The water was extremely warm: Global Warming will kill millions of people, but it made Sunday morning easier. I think it was at or above 70 degrees. High tide wasn’t until 2:00 PM, so we started quite late. We met at the KYC at 9:30, and I don’t think we started swimming until about 11:00. We all arrived at about the same time; I got in at an hour and 28 minutes, and I think we were all in before 1:38.
There may have been a ride to Cadillac and a hike up it, but I’ll have to wait until I hear more to write about that.
## Globals:## Regex to match balanced [brackets]. See Friedl's# "Mastering Regular Expressions", 2nd Ed., pp. 328-331.my$g_nested_brackets;$g_nested_brackets=qr{ (?> # Atomic matching [^\[\]]+ # Anything other than brackets | \[ (??{ $g_nested_brackets }) # Recursive set of nested brackets \] )*}x;# Table of hash values for escaped characters:my%g_escape_table;foreachmy$char(split//,'\\`*_{}[]()>#+-.!'){$g_escape_table{$char}=md5_hex($char);}# Global hashes, used by various utility routinesmy%g_urls;my%g_titles;my%g_html_blocks;# Used to track when we're inside an ordered or unordered list# (see _ProcessListItems() for details):my$g_list_level=0;#### Blosxom plug-in interface ########################################### Set $g_blosxom_use_meta to 1 to use Blosxom's meta plug-in to determine# which posts Markdown should process, using a "meta-markup: markdown"# header. If it's set to 0 (the default), Markdown will process all# entries.my$g_blosxom_use_meta=0;substart{1;}substory{my($pkg,$path,$filename,$story_ref,$title_ref,$body_ref)=@_;if((!$g_blosxom_use_meta)or(defined($meta::markup)and($meta::markup=~ /^\s*markdown\s*$/i))){$$body_ref=Markdown($$body_ref);}1;}
# Check for updates on initial load...if["$DISABLE_AUTO_UPDATE" !="true"]then
/usr/bin/env ZSH=$ZSH zsh $ZSH/tools/check_for_upgrade.sh
fi# Initializes Oh My Zsh# add a function pathfpath=($ZSH/functions $ZSH/completions $fpath)# Load all of the config files in ~/oh-my-zsh that end in .zsh# TIP: Add files you don't want in git to .gitignorefor config_file ($ZSH/lib/*.zsh)source$config_file# Set ZSH_CUSTOM to the path where your custom config files# and plugins exists, or else we will use the default custom/if[[ -z "$ZSH_CUSTOM"]];thenZSH_CUSTOM="$ZSH/custom"fi
is_plugin(){localbase_dir=$1localname=$2test -f $base_dir/plugins/$name/$name.plugin.zsh \||test -f $base_dir/plugins/$name/_$name}# Add all defined plugins to fpath. This must be done# before running compinit.for plugin ($plugins);doif is_plugin $ZSH_CUSTOM$plugin;thenfpath=($ZSH_CUSTOM/plugins/$plugin$fpath)elif is_plugin $ZSH$plugin;thenfpath=($ZSH/plugins/$plugin$fpath)fidone# Load and run compinit
autoload -U compinit
compinit -i
# Load all of the plugins that were defined in ~/.zshrcfor plugin ($plugins);doif[ -f $ZSH_CUSTOM/plugins/$plugin/$plugin.plugin.zsh ];thensource$ZSH_CUSTOM/plugins/$plugin/$plugin.plugin.zsh
elif[ -f $ZSH/plugins/$plugin/$plugin.plugin.zsh ];thensource$ZSH/plugins/$plugin/$plugin.plugin.zsh
fidone# Load all of your custom configurations from custom/for config_file ($ZSH_CUSTOM/*.zsh)source$config_file# Load the themeif["$ZSH_THEME"="random"]thenthemes=($ZSH/themes/*zsh-theme)N=${#themes[@]}((N=(RANDOM%N)+1))RANDOM_THEME=${themes[$N]}source"$RANDOM_THEME"echo"[oh-my-zsh] Random theme '$RANDOM_THEME' loaded..."elseif[ ! "$ZSH_THEME"=""]thenif[ -f "$ZSH/custom/$ZSH_THEME.zsh-theme"]thensource"$ZSH/custom/$ZSH_THEME.zsh-theme"elsesource"$ZSH/themes/$ZSH_THEME.zsh-theme"fififi
classSelectDateWidget(Widget):""" A Widget that splits date input into three <select> boxes. This also serves as an example of a Widget that has more than one HTML element and hence implements value_from_datadict. """none_value=(0,'---')month_field='%s_month'day_field='%s_day'year_field='%s_year'def__init__(self,attrs=None,years=None,required=True):# years is an optional list/tuple of years to use in the "year" select box.self.attrs=attrsor{}self.required=requiredifyears:self.years=yearselse:this_year=datetime.date.today().yearself.years=range(this_year,this_year+10)defrender(self,name,value,attrs=None):try:year_val,month_val,day_val=value.year,value.month,value.dayexceptAttributeError:year_val=month_val=day_val=Noneifisinstance(value,basestring):ifsettings.USE_L10N:try:input_format=get_format('DATE_INPUT_FORMATS')[0]v=datetime.datetime.strptime(value,input_format)year_val,month_val,day_val=v.year,v.month,v.dayexceptValueError:passelse:match=RE_DATE.match(value)ifmatch:year_val,month_val,day_val=[int(v)forvinmatch.groups()]choices=[(i,i)foriinself.years]year_html=self.create_select(name,self.year_field,value,year_val,choices)choices=MONTHS.items()month_html=self.create_select(name,self.month_field,value,month_val,choices)choices=[(i,i)foriinrange(1,32)]day_html=self.create_select(name,self.day_field,value,day_val,choices)output=[]forfieldin_parse_date_fmt():iffield=='year':output.append(year_html)eliffield=='month':output.append(month_html)eliffield=='day':output.append(day_html)returnmark_safe(u'\n'.join(output))
deflinkiff.linked_keg.directory?andf.linked_keg.realpath==f.prefixopoo"This keg was marked linked already, continuing anyway"# otherwise Keg.link will bailf.linked_keg.unlinkendkeg=Keg.new(f.prefix)keg.linkrescueException=>eonoe"The linking step did not complete successfully"puts"The formula built, but is not symlinked into #{HOMEBREW_PREFIX}"puts"You can try again using `brew link #{f.name}'"keg.unlinkohaie,e.backtraceifARGV.debug?@show_summary_heading=trueenddeffix_install_namesKeg.new(f.prefix).fix_install_namesrescueException=>eonoe"Failed to fix install names"puts"The formula built, but you may encounter issues using it or linking other"puts"formula against it."ohaie,e.backtraceifARGV.debug?@show_summary_heading=trueenddefcleanrequire'cleaner'Cleaner.newfrescueException=>eopoo"The cleaning step did not complete successfully"puts"Still, the installation was successful, so we will link it into your prefix"ohaie,e.backtraceifARGV.debug?@show_summary_heading=trueenddefpourfetched,downloader=f.fetchf.verify_download_integrityfetched,f.bottle_sha1,"SHA1"HOMEBREW_CELLAR.cddodownloader.stageendend