PAIP: Day 1

Previous Post

Lisp Syntax and You

Ok, so I’ve actually had a chance to start into the book now that Emacs isn’t so much of a drain. Now I have gone a round or two with Scheme, so the idea of Lisp isn’t that far out for me, but I can’t promise I have the best explanation of why Lisp is… well why Lisp is Lisp. In short, Lisp is build off lists. The name Lisp is short for List Processing, and trust me it’s not just another clever name. I can basically describe you the 80% of what Lisp is in one text diagram:


(operation value1 value2 value3 …. valueN)

And that’s basically it. The very first item in the list is what needs to be done. This can be something like the + symbol that means apply + to all the items in order. So:


(+ 1 2 3) actually means 1 + 2 + 3

So the first thing you might ask, and even if you wouldn’t I’ll still assume you did: What if you want to add something to something else that is in itself added to something. Sorry, that’s my mind trying to ask your question, and it made more sense in my mind. In other words, something like this:


(1 + 2) * (3 + 4)

How is that possible if the first part of the list is the only operator? In that example, it doesn’t make sense, because it’s not in Lisp form.


(* (+ 1 2) (+ 3 4))

As you can see it breaks down to more lists with more operators BUT it does not break the golden rule: Operator Value Value. And honestly, that’s most of the language. There are a few, very few relative to most languages, “special forms” as they’re called, but what that really means are things that break the Operator Value Value rule. As far as Lisp is concerned, I have only run into the most basic of them:


(defun method-name (parameter) (method body))

As you can see, this sets the symbol “method-name” to represent a function body. There’s also:


(setf some-name some-value)

Which again attaches a value to some-name. I do know of more since Scheme works the same-ish way. (I’ve put a little time into Scheme) It has “special forms” like if, cond, and so on, but I’ll comment on them when I hit them in Lisp. The important thing to take away is that pretty much all of Lisp’s structure follows the same damn rule. In this way, it make it fairly easy to interpret from a human side once you get used to all the ().

&@*# the parentheses

I can pretty much guess that if you’ve never seen Lisp, you’ll see all the () and want the get the #@$% off the bus. I get that. It is kind of odd, but in the end there are two things that may help with that:

1) The () helps to interpret it in the long run. After all, from reading what I did above you know that anything between ( and ) follows the rule Operator Value Value right? Well take that a little farther in the example of the more “complex” math thing.


(* (+ 1 2) (+ 3 4))

I know exactly what this will evaluate BECAUSE of the parentheses. I know that every time I see a ( that anything within that ( will be evaluated on it’s own. No question. And for every new ( I know there is something that will be evaluated within that (. This helps to encapsulate functionality for easier breakdown.

2) I personally *#@$ing hate { } and ;. They drive me nuts. After I used Python a while back (and Nemerle and F# and Coffeescript), and as a consequence I got really tired of { } ; in C#. Yeah, there are a lot of (), but that’s all that there are. Just like how Lisp follows the rule of Operation Value Value, it also has syntax uniformity. Would I be happier if Lisp used whitespace? After some thought, no. Why? Because I’m not sure that’s even possible, and it would completely break the ease of interpretation. After all:

*
  + 1 2
  + 3 4

Just doesn’t read too well. Also, even languages like F# need (). Why is that? Because of evaluation:


let someMethod x y =
  x + y

Simple enough right? What if x is a method call?


someMethod someOtherMethod 1 2 3

F# will choke because it will try to shoehorn someOtherMethod into x and 1 into y leaving 2 3 as a source of confusion.


someMethod (someOtherMethod 1 2) 3

Hmmm… looks kind of familiar. Only difference is that it gets annoying having to switch from no () to () in F# due to how it evaluates arguments. At least with Lisp you get uniformity. Now I’m not expecting to sell you on anything at this point, because I haven’t really gotten into anything good. However, I do know that there are some very profound things to come due to watching the SICP videos. Mainly two simply brilliant words (that of course I can’t remember at this moment so I have to check my twits) “Wishful Thinking”. That phrase was the very one that made functional programming make complete sense, and this was after I thought I really had a firm understanding of functional programming.

Let’s Play: Lisp E:1

So a while back, not sure when exactly, I purchased a book on AI for some unknown reason; Paradigms of eh… something something Artificial Intelligence… something something. Anyway, it is highly regarded not just for AI stuff (Though Lisp apparently isn’t the default choice for AI anymore), it’s also supposed to be a great book on programming in general. At least that’s what I was sold on… I think. I also wanted it so I could get a deeper understanding of functional programming. I actually had “shelved” this book (Being I bought the Kindle version I don’t know how I would “shelve” it) for one of my many manymany… jumps to other languages.

For the last year or so I’ve been putting a lot of time into finding some language that fit me right. Most people would have taken a pretty straight forward approach:

  • What is it that I want to achieve?
  • What is it that would make me happy?
  • What is that would solve whatever issues I have with C#?

Instead I decided to just flail my arms, and grab onto whatever I could. And did I ever grab. Ela, Nemerle, F#, Racket, Clojure, Opa, Smalltalk, Prolog, D, Haskell… and probably a dozen others I can’t remember. As I said, “arms flailing”. It’s not that they are bad languages. Actually to my surprise they all are pretty good. Problems like IDE support, community strength, ability to find hosting (COMPLETE BITCH), and clear cut libraries for web development were things that came up a lot. For example D: Probably the most impressive language I have ever seen hands down. The meta programming potential is off the charts. Problem? Web development is not really the goal of most D users.

So I kept finding myself trying to make F# work. After all, I’ve been dealing with the .Net stack for over a decade, AND it is a by gosh true functional language. It should be a no brainer… but as nice of a language it is, the support sucks. It took Microsoft… 4? years in order for MS Test to be able to pick and run Unit Tests. FOUR @#!%ing years. Not to mention how mediocre the Intellisense support which has only become livable in 2012. And if you think I’m just being a #%^@ to Microsoft because I can; That’s nowhere near the truth. My anger comes from failed expectations from a company I expect the best from. Fact of the matter is: If you like C#, it’s probably one of the best supported languages out there… from what I’ve seen it’s the best. But to me, it just doesn’t work for me anymore.

When I finally decided to drop the F# for good, I found myself frustrated to say the least. This basically meant I had to go with a far less supported, open source language for .Net (Which there are a couple of really good ones) that just doesn’t have the support (Understandably) that C# has, or I’d have to for sure put .Net behind me for good outside of work. This also meant I would have to leave my beloved Resharper behind. And if you’ve never used Resharper before, you have no idea how hard it is to walk away from that too.

So within the last couple weeks, I’ve taken another look into the Lisp in a Box for Windows, I was well on my way. Now my only obstacle between myself and Lisp was Emacs.

Now before any Emacs users get all Nerd Raged, understand that I’ve spent most of my programming life in the comfy, heavily GUI based world of Visual Studios. Emacs is about the closest to Not Visual Studio that I can imagine exists. It’s like the evil Visual Studio double from that other dimension in Star Trek. The one with a mustache and goatee. Pretty much everything is either keyboard based, or at least keyboard accessible. Being that Emacs itself pre-dates the household available mouse, I’m guessing somewhere along someone said, “We’ve lived without mice this long, so %@#! ’em!” Well maybe not that harsh, but whatever. Point being, I thought I was pretty pro keyboard until I met Emacs. Was I wrong. Even with the estimated 1.4 bagillion (+/- .1 bagillion) key shortcuts Resharper has, I wasn’t prepared the least bit. The first 15 minutes almost had me convinced that this was in fact one of the many literary levels of Hell. It’s not just that Emacs uses key combinations, it’s that when paired with Lisp tools like SLIME it becomes a nightmarish extravaganza of “WHAT THE #$@# JUST HAPPENED!?!”

Oh sorry you meant to hit Ctrl + x, Ctrl + b for a pretty display of open files? Too bad because you didn’t hold Ctrl for b, and now you have to chose some random !#@ one line command prompt to find the file by pressing up and down.

Oops? Did you mean Ctrl+x, 2 so you could split the screen? Sucks for you since you press Ctrl + x, 1 which kills all but one screen.

The level of frustration reached a limit reserved only for POS video baby monitors that CANCEL OUT EVERY @#*$ING WIRELESS SIGNAL FOR A 12 BLOCK RADIUS. So as you can imagine, it didn’t go so well this first time. HOWEVER, like the good little monkey that I am, I was able to finally get down some useful controls:

Ctrl + x, 2 : Open up another screen within Emacs for a split screen look… For a real laugh, do this over and over again. Emacs will just keep splitting screens… still can’t figure out how to close them one by one though.
Ctrl + x, o : Switch between open screens within the current Emacs instance
Ctrl + c, Tab : Auto complete… An odd departure from what I’m used to from Visual Studio. Instead of a small selection box, it temporarily opens up another window with various possible keywords to choose from
Ctrl + x, Left Arrow/Right Arrow: Cycle through every “buffer”. Buffer being the generic name for “open stuff” which can be files, or programs like SLIME.
Ctrl + x, Ctrl + b: Get a list of all “buffers” to chose from
Ctrl + x, 1: Close all windows but one
Ctrl + ?, ?: Somehow open up three more windows of the same REPL (basically like a real time compiler and intrpreter) and be able to see yourself typing the same @$#*ing thing in for windows at the same time.

As you can see, I have a long way to go though. However, I am happy to say that I can at least now use the book.

FSharp: Using the Pipe Operartor to Chain Methods

This is a real quick and simple thing, so uh yeah… One of the things I detest in F# is having to use the “normal” method chaining built into C#. FOr instance with the StringBuilder class:

open System.Text

let something =
    StringBuilder()
      .Append("hi")
      .Append("there")
      .Append("!")
      .ToString()

Now for C# that is acceptable.. but not for F# when the |> operator is involved. I want this:

let something =
  StringBuilder()
    |> Append "Hi" 
    |> Append "There"
    |> Append "!" 
    |> ToString()

Which is actually a lot easier than it might seem. When using the |> the next method has to take in the last method’s result. As long as the last parameter of the method matches up with the result of the last, you’re gold. This will NOT work:

let something =
  StringBuilder()
    |> Append "Hi" 

There’s no StringBuilder to be used for that Append method, so it breaks. Remember, the last parameter of the next method has to be the same as the preceding result. So…:

  let append (text: string) (builder : StringBuilder) =
    builder.Append(text)

  let toString (builder : StringBuilder) =
    builder.ToString()

As you can see, the appendBuiler method has a signature of StringBuilder -> string -> StringBuilder meaning it takes in a string and then a StringBuilder. Now because of currying, this is complete viable:

  appendBuidler "Hi" ?

Where the ? will be filled in at some point. All it knows is that the ? will be a StringBuilder. With this in mind, the chain kind of looks like this:

  StringBuilder() |> append "Hi" ? |> append "There" ? |> append "!" ? |> toString ?

Where every ? is a place holder for the result of the previous method.

Does this save any time? Eh probably not. However, it does show the how useful the |> can be when it comes to workflow like design. For example:

  database |> openAConnection |> getAllUserNames |> closeTheConnection |> Seq.length > 0 |> shouldBeTrue

See if you can figure that one out.

Getting Started with Nuget and Visual Studios 2012… or whatever it’s called now.

So if you’re like me, and I’m guessing you are since you are reading this, you have a sort of idiotic reaction to anything that takes setting up. This may have prevented you from using anything on linux, setting the clock in your car, and using Nuget. Now up until this point I have tried really hard to avoid Nuget due to its… unfortunate earlier life. However, this wasn’t due to the concept, but more of the completely insane mass assembly hoarding functionality that made it about as useful as … something that isn’t useful. Sorry, couldn’t come up with anything funny. Surprised, I’m sure.

So anyways, after about two hours of pure pain this afternoon, I got it to work. And it works LIKE IT SHOULD HAVE THIS WHOLE @#@!ING TIME.

Ok first step is to just create a project. Excitement! One thing to make sure, or at least for this random mass of pointless I call a tutorial, that you have the “Create directory for solution.” checked.

Next is to create a second project. Yeah I know you weren’t ready for something as complicated as a solution with two projects, but that really doesn’t concern me.


One note is that to make life easier make sure both projects are on the same level of the solution folder hierarchy thing… hence the awesome red trapezoid-ish thing in the picture.

Next up is opening up the package manager that is nestled so comfortably in TOOLS -> Library Package Manager -> Package Manager Console:

This is basically a nifty command line like tool for Nuget which I personally prefer.

For the first project I added… waiting for Paint to open my awesome png that apparently is so awesome it is causing paint to freeze up. That’s right folk, freezing Paint is the true test of awesome. It’s that or Gimp is jealous that I used Paint. Not sure. Anyways, for the first project I added xunit.

Something of note is that the name of the project you are installing something too is known by the Package Manager Console. Really nice feature to assist with selecting the right project.

For the second project I added FsUnit.xunit… And somehow the image I just loaded into Gimp was almost instantaneous. Funny how that is.

Yippee. When you go to the directory through Windows Explorer you’ll notice the top level folder now has a packages folder.

This will be the folder all projects will refer to so you don’t have 20 different copies of Nunit for the 20 unit testing projects you have. Now if you go one step into FirstProject you’ll see that a packages.config file has been added. It is just a file that tells Nuget what packages (Assemblies) the project needs in the packages folder.

Almost done. The one last thing that is actually pretty nice is having Nuget/Visual Studio get all needed packages that are missing on Build. Right click the Solution item in the Solution Explorer -> Enable Nuget Package Restore

So now what you can do is close the solution, delete that top level packages folder, reopen the solution, build, and see that the top level packages folder has been recreated. This is a really nice feature that can help with sending a solution to source control, and not have to take the outside assemblies with it.

So there you go… Seriously that’s all I’ve got. Go home.

F# and picking a method based on an if statement

I actually saw this first in SICP, but then proceeded to see if F# can do this. Basically it’s an if statement that selects a method to use based on a clause, and then evaluates using two parameters.

  let add x y = x + y
  let sub x y = x - y
  (if 0 = 0 then add else sub) 1 2

As you can see, the parameters stay the same but the actual method called doesn’t. The way it’s written, it evaluates to:

  add 1 2

However, were I to switch the 0 = 0 to 0 = 1 then:

  sub 1 2

Not sure how this would apply to real life, but knowing is the first step.

F# and assigning operators as methods

Once again I have fallen back on F# as the main language of interest. At least until I pick the next one to replace it. Not like I’m wishy washy or anything.

One of the more interesting things about languages like Scheme or Lisp is that nothing is sacred. You can assign characters to methods, and this is possible in f# also.

Here’s an example of a “default” way of defining %% as adding two numbers together.

  let (%%) x y = x + y
  // 1 %% 2 results in 3

As you can see, the %% just looks like a typical operator method. However, it can be changed so that it is actually before the arguments:

  let (!%%) x y = x + y
  // !%% 1 2 results in 3

For anyone who has used Lisp, this should look familiar. It is called Prefix Notation.

Now for something a little more interesting: Take the List.map method. It basically takes a list and applies a method to every member to create a new list. For the C# people, it’s equivalent to someList.Select(x => method(x)). Say you wanted to create a method that just takes a list and “maps” a method to add one to each item.

  let result = List.map (fun y -> y + 1) [1;2;3;]

Pretty simple. Now what if you want to make this a method that takes in a list and applies the same method above to each item?

  let addOne x = List.map (fun y -> y + 1) x
  // addOne [1;2;3] results in 6

Pretty simple again. Now in one more step you can assign operators to do the same:

  let (!+) x = List.map (fun y -> y + 1) x
  // !+ [1;2;3] results in 6

Now I realize this may seem trivial, but it’s actually quiet useful when you start talking about Domain Specific Languages since this allows methods to use non Alpha names.

Coffeescript versus Javascript example for FUN

Coffeescript:

window.someList = [1, 2, 3, 4, 5]

addOne = (item) ->
  1 + item

window.runThings = () ->
  addOne item for item in someList

Coffeescript compiled to JavaScript:

(function() {
  var addOne;
  window.someList = [1, 2, 3, 4, 5];
  addOne = function(item) {
    return 1 + item;
  };
  window.runThings = function() {
    var item, _i, _len, _results;
    _results = [];
    for (_i = 0, _len = someList.length; _i < _len; _i++) {
      item = someList[_i];
      _results.push(addOne(item));
    }
    return _results;
  };
}).call(this);

Fizzbuzz in Scheme/Racket

No idea why I did this…

(define (fizzbuzz listIn [currentList empty])
  (define (showWhich itemToTell)
    (let ([testString
           (string-append
            (if (= (modulo itemToTell 3) 0) "Fizz" "")
            (if (= (modulo itemToTell 5) 0) "Buzz" ""))])
      (if (= (string-length testString) 0)
          itemToTell
          testString)))
  (define (add-head-to-list itemList listTAddTo)
    (append listTAddTo (list (showWhich (first itemList) ))))  
  (cond
    [(null? listIn) currentList]
    [(null? (rest listIn)) (add-head-to-list listIn currentList)]
    [else (fizzbuzz (rest listIn) (add-head-to-list listIn currentList))]))