Week 41: Pascal

This week’s language, Pascal, can be summed up in one sentence: Pascal is that CS teacher that always tells you about how you need to write more comments. Pascal forces you to write well-organized code; global variables at the top of the file, followed by function definitions (with all their local variables declared at the top, naturally), followed by the main function. When compared to modern dynamic languages, this paradigm of up-front variable declarations may seem a little dated, but I found it a nice change to write in a language that forces you to put a little extra thought into how you organized your code.

Cutting to the chase, here are the results of this week’s dabbling:

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
program HelloPascal
uses crt;
var
  { You need your global variables defined up front }
  result: Integer

{ Functions and procedures are defined at the top }
Procedure sayHelloTo(var name: String);
  begin
    writeln("Hello, ", name);
  end
end;

Function myfunc(var input: Integer): Integer;
  var
    { You have to declare your local variables at the top of functions }
    toReturn: Integer;
  begin
    toReturn := input * input; { Square the input }
    myfunc := toReturn / 2; { Divide it by two }

{* Main program starts here *}
begin
  { If you haven't picked up on this yet, comments are enclosed in curly braces}

  { Here's a procedure (procs are like functions but without a return value) }
  sayHelloTo('Pascal');

  { Here's a function }
  result := myfunc(1);
  writeln("The result is ", result);
end.

Thanks for reading; I’ll see you next time.

Week 40: HMMM

I know I’ve already done Assembly, but I was recently at Harvey Mudd for a visit, which I think justifies my choice of Harvey Mudd Miniature Machine Language for this week’s post. During my visit I sat in on a CS lab and tried my hand at a couple of the problems, one of which was this assembly-based implementation of a linear congruential generator algorithm (a pseudo-random number generator). Details on the spec can be found here, and here is my very own implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
00 read r1     # input a (multiplier)
01 read r2     # input c (increment)
02 read r3     # input m (divisor)
03 read r4     # input X_0 (seed)
04 read r5     # input N (number of pseudo-random numbers to print out)

05 jeqzn r5 12      # Iterate r5 times
06 mul r10 r1 r4    # Using r10 as scratch space, carry out a*X_n
07 add r10 r10 r2   # carry out the addition in a*X_n + c
08 mod r4 r10 r3    # carry out the modulus in (a*X_n + c) % m
                    # .. store the result in r4
09 write r4         # Print out the pseudo-random number
10 addn r5 -1       # Count downwards towards zero
11 jumpn 05         # Iterate!

12 halt             # And we're done!

Thanks for reading, and I’ll see you next week.

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!