Week 39: Algol

Another short post this week, everyone.

The title says it all. This week’s language: ALGOL. Short for Algorithmic Language, this language made it’s debut 1958 back when people still programmed using a hole-punch. Unfortunately, I don’t have a hole punch handy, so a keyboard will have to suffice. Here you go (in the original ALGOL 58, no less), a program to find the maximum of a list of numbers (and by maximum I mean the number with the largest absolute value):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
begin
    integer N;
    Read Int(N);

    begin
        integer array Data[1:N];
        integer runningMax;
        integer i;
        runningMax := -1;

        for i:=1 step 1 until N do
            begin integer val;
                Read Int(val);
                Data[i] := if val<0 then -val else val;
            end;

        for i:=1 step 1 until N do
            runningMax := if Data[i] > runningMax then Data[i] else runningMax;
        Print Int(runningMax)
    end
end

Looking at those natural-language for loops and conditional assignments, you won’t believe it’s not Ruby :P.

P.S. For those of you who might be interested, here’s my source.

Week 38: Assembly

Coding in Assembly is a little like building a lightsaber: something that every programmer should do, but also something no programmer should do twice. The last (and only) time I coded in Assembly was for this CTF, and I haven’t missed it since. Nevertheless, I thought it would be a good language to share this week.

I have an idea. Let’s take something easy, and make it harder

For this week’s program, I’ll be implementing addition (in x86 assembly). Tricky stuff. For an extra twist, if the result is less than or equal to 5, it gets multiplied by 2 (just because).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
push 2 ; Set up the stack with the numbers we want to multiply.
push 2 ; 1 & 2 in this case

pop EAX ; pop the top value of the stack into EAX (a general purpose register)
pop EBX ; pop the new top value of the stack into EBC (another general purpose register)
add EAX, EBX ; add the two values (store the result in EAX)

cmp EAX, 5
jg not_lesser

imul EAX, EAX, 2

not_lesser:
    ; no-op, just skip the multiplication step

At the end of execution, the result of the operation should be stored in EAX.

Week 37: Elixir

I’m still catching up, so this post is going to be on the short side.

This week’s language is, as you can probably guess from the title, Elixir. Elixir is a dynamic, functional language based on Erlang (and, as far as I can tell, uses the Erlang runtime). Based on what I’ve seen so far, the best way to describe Elixir is as Ruby but with a much bigger focus on functional programming. Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
defmodule LooksLikeRuby do
  def this_syntax_is_familiar do
    "This function declaration is almost valid Ruby (except for that extra 'do')"
  end

  def but_with_a_twist(x) when is_integer(x) do
    "Look at that pattern matching!"
  end
end

IO.puts LooksLikeRuby.this_syntax_is_familiar
IO.puts LooksLikeRuby.but_with_a_twist(2)

IO.puts "\nYou can also use anonymous functions"
the_function_with_no_name = fn a, b -> :math.sqrt(a*a + b*b) end
hypotenuse = the_function_with_no_name.(3, 4)
IO.puts "A Pythagorean tripe: 3, 4, & #{hypotenuse}"

IO.puts "\nAnd now for another mainstay of the functional style: pattern matching!"
msg = {:error, 404, "The page you requested could not be found"}
case msg do
  {:success, code, message} ->
    IO.puts "Success! Code: #{code} returned with message \"#{message}\""
  {:error, code, message} ->
    IO.puts "OH NO! An error (code #{code}) occured, returning message \"#{message}\""
end

Week 36: Nimrod

Let’s get one thing straight right off the bat: I know it’s not Week 36. It’s Week 38 and I’m a little behind schedule. In light of this, the next couple of posts will be quite short, hopefully just until I get caught up.

tl;dr: Imagine Python if it was statically typed and compiled to C

That’s basically it, minus some syntactical details. Check out the homepage if you want to learn more. Otherwise you can take a look at my code below, which prints the nth number of the Fibonacci sequence (this algorithm is unbelievably inefficient, but I wanted to demonstrate Nimrod, not good algorithm design).

1
2
3
4
5
6
7
8
9
10
11
var n: int = 10 # Static typing

echo(fib(n))

proc fib(n: int): int = # Functions are called "procedures", or "procs" for short
  if n == 1:
    return 0
  elif n == 2:
    return 1
  else:
    return fib(n-1) + fib(n-2)

Week 35: PHP

I know I’m behind schedule, so I’ll skip the prologue. Here’s this week’s language:

PHP

Here have code (it’s a web-page that generates a pseudo-random integer whenever you load the page):

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html>
  <head>
    <title>PHP RNG</title>
  </head>
  <body>
    <h1><?php
      $lucky_number = rand();
      echo "Your lucky number is <b>$lucky_number</b>"
    ?>
    </h1>
  </body>
</html>

Short and sweet. The important part of PHP is having code in a web-page run server-side, changing key parts of that page, and there you have it.

Week 34: Obj-C

Hi again. I’ve been super busy lately (college essays and all), so I’m a) a little behind and b) going to be serving up some shorter posts for a while.

Let’s get started, shall we?

Imagine what would happen if C and Smalltalk had a baby, and then that baby was given an iron man suit and financed by a multi-billion dollar company, and you’ll have a pretty good idea of Obj-C. Even before you add all the iOS/OSX specific libraries and the Xcode development environment, Objective-C almost more of an API than a language (just look at it’s standard library). In keeping with this spirit, this week’s program is going to consist mainly of me picking a random, interesting-looking Foundation class and running with it.

Here have code

My code uses the NSLinguisticTagger class, which allows you to analyze a string a tag the tokens within that string as parts of speech. Here I’m using it to remove all adjectives from a given string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        NSString * sampleString = @"The quick brown fox jumped over the white fence";
        
        // Ignore whitespace & punctuation, join names
        NSLinguisticTaggerOptions options = NSLinguisticTaggerOmitWhitespace | NSLinguisticTaggerOmitPunctuation | NSLinguisticTaggerJoinNames;
        
        NSLinguisticTagger * tagger = [[NSLinguisticTagger alloc] initWithTagSchemes: [NSLinguisticTagger availableTagSchemesForLanguage:@"en"] options: options];
        tagger.string = sampleString;
        
        NSRange targetRange = NSMakeRange(0, [sampleString length]);
        
        // Build a new string without adjectives
        NSMutableString * stringWithoutAdjectives = [NSMutableString stringWithString:@""];
        [tagger enumerateTagsInRange: targetRange scheme: NSLinguisticTagSchemeNameTypeOrLexicalClass options: options usingBlock: ^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) {
            if (![tag isEqualToString:@"Adjective"]) {
                [stringWithoutAdjectives appendString: [sampleString substringWithRange: tokenRange]];
                [stringWithoutAdjectives appendString:@" "];
            }
        }];
        
        // Remove trailing space
        [stringWithoutAdjectives deleteCharactersInRange:NSMakeRange([stringWithoutAdjectives length]-1, 1)];
        
        NSLog(@"\"%@\" seems a little verbose. Try \"%@\" instead.", sampleString, stringWithoutAdjectives);
        
    }
    return 0;
}

Output: "The quick brown fox jumped over the white fence" seems a little verbose. Try "The fox jumped over the fence" instead.

Thanks for reading. See you next time.

Week 33: AWK

This week’s post is about a language/tool that I’ve been wanting to learn for some time: AWK. AWK (or awk) is a UNIX command-line tool that comes with its own interpreted language for text manipulation and analysis, and it should be useful in whipping up all kinds of script-fu. Let’s get started, shall we?

According to Wikipedia

awk programs consist of “a series of pattern-action pairs”. In other words, ack programs consist of chained statements of the form

1
condition {action}

When analyzing a file, awk first breaks it up into “records” (lines), and then processes each line sequentially, evaluating each action whose condition is true for the current line. Additionally, the BEGIN and END conditions cause their respective actions to be evaluated before or after the file is analyzed, and pattern1, pattern2 matches every record starting with the one that matches pattern1 up to the one that matches pattern2.

It is worth noting that either the condition or the action can be blank, in which case condition defaults to matching everything, and action defaults to printing the line.

The awk language has a full suite of standard functions, like arithmetic, printing, writing files (using the UNIX > syntax), piping, functions, regexps, and much more. I won’t get into a whole lot of detail here, and instead will point interested parties to some helpful resources.

With that out of the way, it’s time for the main event.

Start the music!

This week’s program is going to be an awk script to read a file and play Morse code based on it’s contents. Lines starting with a “–” or the word “dit” will be dits, lines starting with a “_” or the word “dah” will be dahs, and blank lines will be character breaks. Here we go.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function dit() {
  print "\a"
  system("sleep 0.2")
}

function dah() {
  print "\a"
  system("sleep 0.5")
}

function char_break() {
  system("sleep 0.5")
}

/^(-|dit)/ { dit()        }
/^(_|dah)/ { dah()        }
/^$/       { char_break() }

I’ve fine-tuned the timings to sound right to my inexperienced ear, but forgive me if they are not spot-on.

You can run this program by saving it as morse_parser.awk, saving the morse you want to play in morse.txt, and running awk -f morse_parser.awk morse.txt. Thanks for reading, and I’ll see you next week.

Week 32: C

This week’s language is C. A tab staid, I know, but I’ll do my best to keep it from being too boring.

“How?”, I hear you ask

Funny you should ask that.

<INCEPTION NOISE>

DUHNNNNNNNNNNNNNNNNNNNNN

I could write something like a really fast sort, because this is C, and C is fast. But that brings us to the problem of really fast C code being not that interesting to write about (unless I start getting really passionate about pointers… you never know). To remedy this malady1, I’m going to avoid the problem entirely by writing some code in Ruby.

1
2
3
4
5
6
7
8
9
class NotBoring
    def doSomethingInteresting
        puts "Knock Knock"
        puts "Who's there?"
        puts "Boo"
        puts "Boo who?"
        puts "Don't cry"
    end
end

And now to write the same exact code in C!

Ruby, at its base, is implemented in C and therefore allows you to write extensions in pure C. Here we go (in the file notboring.c):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "ruby.h"

static VALUE not_boring_class; // VALUE is the data type for a ruby object

static void doSomethingInteresting() {
  printf("Knock Knock\n");
  printf("Who's there?\n");
  printf("Boo\n");
  printf("Boo who?\n");
  printf("Don't cry\n");
}

void Init_notboring() {
  not_boring_class = rb_define_class("NotBoring", rb_cObject); // Defines a ruby class that inherits from Object
  rb_define_method(not_boring_class, "doSomethingInteresting", doSomethingInteresting, 0); // Defines a ruby method for the class NotBoring called doSomethingInteresting that will evaluate the given function with 0 arguments
}

The C code needs some supporting ruby to build a Makefile (this goes in extconf.rb)

1
2
require 'mkmf'
create_makefile('notboring')

That’s it! Now just run ruby extconf.rb and make and you’re ready to fire up irb, run require './notboring and play around with the new class, knowing that it’ll be extra speedy due to C’s hefty natural advantage.


  1. Heyoo!

Week 31: SCSS

Hi there. I know there haven’t been any posts in a while, but that’s not because I haven’t been coding. In fact, I have a backlog of languages to write about. Let’s get started.

I don’t need any SASS

First, a little history:

In the beginning, there was HTML, And it was pretty boring.

So some people said, “Let there be CSS”.

And there was CSS, And things were suddenly not so boring.

But some other people said, “This is still kind of boring.” “Let there be variables and loops and things.”

And there were variables and loops and things, And things were even less boring, And it was called SASS.

BUT THEN the first group of people said, “Hold the phone. SASS syntax is not a strict superset of the existing CSS standard!”

And the second group said, “Alright, let there be curly brackets and semicolons.”

And there were curly brackets and semicolons, And it was called SCSS, And things were slightly more boring, But it’s the standard now, so live with it.

How’s that for a creation story?

Variables and Loops and things

My adventure in the land of SCSS comes in the form of a Rails app, using Bourbon Neat with a dash of Bitters as the frontend framework. To decrypt that last bit, Bourbon is a SCSS mixin library that turns your stylesheet’s awesome factor up to 11, Neat is a SCSS grid framework, and Bitters is a scaffold for your stylesheets (all three are maintained by Thoughtbot).

You can see the results at http://corresponder.herokuapp.com/

P.S. Shout out for my new favorite serif font: Bitter (the similarity to the frontend framework is coincidental).

The meat of the code can be seen in letters.css.scss:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$letter-columns: 8;

.wrapper {
  @include outer-container;

  @include pad(0 0 20 0);

  .headings {
      @include span-columns(4);
      @include shift(2);
      @include omega;
  }

  .letters {
    @include span-columns($letter-columns);
    @include shift(2);
    
    $half: $letter-columns / 2;
    .letter {
      @include span-columns($half of $letter-columns);
    }

    .your-letter {
      @include span-columns($half of $letter-columns);
    }
  }
}

Represented here are some of the things that make SCSS awesome.

  • Variables like $letter-columns make your code much more DRY.
  • Mixins like @include span-columns(4) do the same thing by allowing you to give inheritance-like behaviors to your styles.
  • Nesting makes your code more expressive (see below).

Without nesting, your stylesheets might look like this:

1
2
3
4
5
6
7
8
9
10
11
div.main {
    // Some stuff
}

div.main a {
    // Styles for child anchor
}

div.main a:hover {
    // Blah blah blah
}

With nesting, that becomes:

1
2
3
4
5
6
7
8
9
10
11
div.main {
    // Some stuff

    a {
        // Styles for child anchor

        &:hover {
            // Blah blah blah
        }
    }
}

Pretty cool.

That’s it for now. Watch out for the next installment!

Week 30: Smalltalk

Hi all! This week’s going to be short (and I really mean it this time).

tl;dr: Smalltalk

Smalltalk. The link’s right there in case you want to look it up. I’m a little pressed for time, so I’m going to get right to the program.

The Program

Smalltalk’s shtick is the “message” construct. Messages are like methods in that they are sent to receivers, and the receivers can respond with an answer (a return value). As in Objective-C (my first language, one that inherited a lot from Smalltalk), in Smalltalk messages can have keywords interspersed with arguments, which can lead to more readable code. For example, instead of something like Rectangle.new(100, 100) you could write Rectangle width: 100 height: 200.

Well, you know what they say: if it’s worth doing, it’s worth overdoing :P.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Object subclass: Rambler [
  Rambler class [
    so:something walksInto:aPlace andThe:person looksUpAndSays:thePunchline [
      'Let me tell you a joke' printNl.
      ('So, ',something,' walks into ',aPlace) printNl.
      ('And the ',person,' looks up and says, "',thePunchline, '"') printNl.
      '' printNl.
      'Can you believe that?' printNl.
    ]
  ]
]

Rambler so: 'a guy' walksInto: 'a bar' andThe: 'bartender' looksUpAndSays: 'Stop telling these stupid jokes'.
'===================================' printNl.
Rambler so: 'an alien' walksInto: 'a space station' andThe: 'bartender' looksUpAndSays: 'Why is there a bartender on a space station?'.

And one more thing

Before I wrap up this post, I just want to comment on how nice the multiple keyword message syntax makes things look. For example, if x is an array, x at:1 put: 1337 inserts 1337 at index 1 of array x. Isn’t that nice? OK, I’m done now.

KTHXBAI.

P.S. The docs aren’t great. I had to google for a long time just to find a complete example of a GNU Smalltalk class declaration