Tag Archives: programming

Why I use Rust

Lambdas! And decent docs.

Vomit

You bloated oaf, gorging on galaxies of glut. Go away. You and your UML, your pathetic paradigm. “Object-oriented!” you cry, diverted from the devastation of your application. Failing to find the chink in the armor, the aroma of smoke unsettles your strategy. “Scalability! We’ll scale the scales!” Disillusioned with lubrication by refactoring, factories, actors, event driven development. Drizzles of gristle. Is programming still fun? Functional, formulae conjunctional, cool, casual, actual work done. For fear not the lambda, the greek grapheme of ephemeral memorable purpose. Pose the function as transformer, reformer of data from input to output to input to output to input. Slews of loops, looping the function again. Again. Again. Break! How can you construct a deductive mechanism for deducing data from consumable samples, if not in Lisp? Or if not that, in OCaml? Oh come on, there’s loads of lovely ladies carrying coy caricatures of lisps, little lilting voices, smut for the C-smitten. Crackers to your brackets, but barely a soul seeks murky, mechanical LISP. Lots of irritating superfluous parentheses? No. “ML.” A moan, a mouthful of semantically laden syllabic syntax. The rub: Ruby, used usually in the uncool procedural sense, incidentally features the little fucker. Lambda, you dog! Ruby dooby do! Python’s on the list, Lua not excused, it’s there too. Odds are, philistine, your tool of choice has lambda in its toolkit, so zarking use it. If you suddenly saw the earth beneath your eyes realizing you could fly, would you reduce yourself to the banality of walking? Wake up. Procedural programming is impoverished. Appreciate artificial intelligence, barely a leap for lisp gents, or more generally, lisperati. Objects are unnecessary. Data defined by fiat, ha! Data’s declared by necessity, flowing from the form of the transformation: Integral to a collection of cows coldly calculating calculus to reality. Really. If the function makes steak, grant not anything but boves. There’s your objective. Objects are trash, nasty, thrashing not solving but revolving on nonproblems of encapsulation. Try algebraic data types on for size. As a small consolation, consult the folks who gave the gravy, namely garbage collection; remember, Lisp invented it. If not for Lisp, then conditionals wouldn’t be. B being C’s predecessor, son of BCPL, son of CPL, son of ALGOL, son of FORTRAN, son of assembly. That’s a long line and a lot of time to wait for the second coming of the lambda calculus, Church’s research not crucified but sadly set aside. Sigh, sheer boredom with annoying von Neumann machines must have been McCarthy miraculous leap to Lisp. The future is functional, finally. And it’s stuck in 1960 where real work, not XML, was done. The past is Prolog; the rest formatting, an exercise for the writer.

Why I don’t use Groovy

It’s a Python/Ruby knockoff. If you like Python or Ruby but want the JVM, just use Jython or JRuby.

The best thing about Groovy, and the thing that separates it from Java, is closures. Though it looks like they’ll be coming to Java soon, so stay tuned.

SPARK/Ada

Cheetah wearing an M1 helmetThat’s a Cheetah wearing an M1 helmet. Yeah, SPARK/Ada is that goofy. Pascal was considered unsafe for military projects, so they made Ada. Then Ada was considered unsafe for military projects, so they made SPARK, lulz.

Modern languages with type safety include Haskell, OCaml, and Coq. Because our critical systems are too precious for antiquated technology.

Why I use Mathematica

The docs are FANTASTIC. Let’s say you want to compose functions. Google mathematica composition. The relevant doc page is super easy to find, and the content of the docs are easy to understand.

Prefix, Postfix, Newfix, Bluefix

My, my, look at all those notations. You can infix: 2 + 2. You can prefix: + 2 2. You can postfix: 2 2 +. All three notations are perfectly arbitrary for the purposes of mathematics. (2 + 2) * 3 = 12, so what’s really different about these codes?

Code 1

x = 2 + 2
y = x * 3
print(y)

Code 2

x := 2 plus: 2
y := x times: 3
y print

Code 3

2 2 + 3 * print

Code 4

(let* (
   (x (+ 2 2))
   (y (* x 3)))
      (print y))

Code 1 is typical of procedural programming (Python1, C, Basic, Pascal). You declare variables, store data in variables, and display variables.

Code 2 is typical of object oriented programming (Java, C++, Ruby2, Smalltalk2). You instantiate objects, send messages to objects, and display objects.

Code 3 is typical of stack programming (Factor, Joy, Forth). You push values onto the stack, push functions onto the stack, and display the stack.

Code 4 is typical of functional programming (Haskell, ML, Erlang, Lisp). You pass expressions, evaluate expressions, and display expressions.

But what’s really different?

Codes 1 and 2 are fundamentally the same: they’re stateful computations. Code 1 stores state in variables, Code 2 stores state in objects, but it’s all the same. Code 2 is syntactical sugar for Code 1. And Code 1 is syntactical sugar for:

Code 0

add x,2,2
mul y,x,3
put y

In other words, you’re still explicitly performing register transactions. Do this calculation then STORE THE RESULT IN HERE. Do that calculation then MOVE THE BYTES TO THERE.

By contrast, Codes 3 and 4 are an island all their own: they’re functional computations. Instead of manipulating machine registers, they manipulate mathematical expressions3. Code becomes data becomes code again; you can pass functions as arguments to other functions as if they were pure mathematical constructs. Code 4 named the expressions “x” and “y”, while Code 3 didn’t, but as Code 3 shows, naming isn’t really necessary, it’s just a convenience.

So what’s really different? Functional programming provides a whole new level of abstraction, one that allows you to write more complex code than you could in low-level languages like Java. Really. Do you like moving bytes around, or would you prefer to leave that as an exercise for the compiler?

1 Python has functional elements, but they’re underused. Most Python programmers aren’t even aware that Python has list comprehensions and anonymous functions.

2 Ditto for Ruby and Smalltalk. They have blocks, and therefore can do functional programming, but it’s not emphasized. With all the OOP hullabaloo, the incentive is to write stateful methods instead of pure methods, especially in Ruby where the line between f and f! blurs because the result of the last evaluated expression is always returned.

3 Most functional languages have stateful capabilities, but they’re strictly only necessary for specialized calculations such as pseudo-random number generation, concurrent programming, and I/O. Also, functional language compilers must be stateful in order to compile functional programs that provide the abstraction of pure, stateless code. (see Haskell).

Haskell Type Transparency

program it patrick

Coding is often a matter of looking up API calls, chaining them together, and outputting the result. In a dynamically typed language like JavaScript, it can be difficult to determine exactly what kind of thing a function returns. For example, a JSON parsing library might have the function:

function parse(data) {
   ...
}

According to the docs, parse() takes JSON text and turns it into a JSON object. But will parse() return a tree literal? A manipulable JSON object? A callback that returns a JSON object? Does parse() return anything at all? Does parse() modify data in place to become a JSON object? What is the type of data anyway? A string? A URL to a location containing a string?

In statically typed languages, types are more transparent:

parse :: String -> Tree String
parse = ...

This Haskell code defines parse as a function which accepts a string and returns a tree of strings. No more slogging through Google results just to see how to use API calls. Haskell’s type strictness is a blessing in disguise; although it may seem inconvenient to specify types up front, in the long run, the code is more readable and more robust.

There’s the JavaScript bayou of playtesting combinations of o.foo(), o.bar(), o.foo(o.bar()) in the interpreter until o responds to one of them.

There’s the scurvy C, where data is could be a long, or a pointer, or a pointer to a pointer, or NULL. The type system is more what you’d call “guidelines” than actual rules.

Then there’s the calm, steady stream of lucidly typed Haskell.

Single Assignment C Misnomer

In a sequence of variable definitions, the scope of a variable starts with the left-hand side of its definition and either reaches down to the end of the function, or, provided at least one further definition of a variable with the same name exists, to the right-hand side of the next such definition. This measure allows us to reuse variable names.

SAC Tutorial

In other words, Single Assignment C, isn’t.

Chicken Scheme for the Soul

chicken scheme logoRemember the child-like glee of writing your first computer program? It’s damned hard, but also fun. You feel in control, the god of a tiny universe. Anything is possible! But as you’ve matured, your smile may have faded. Programs are no longer for enjoyment, but for verification. Design, unit test, implement, commit, doze, repeat. Has programming become a bore? It’s time to rekindle the fire.

If you haven’t learned Lisp yet, it’s highly recommended. Don’t worry that your boss still wants you to use Java. Don’t worry that it feels… alien. When it finally clicks, you’ll learn to program as you never have before, and you can take that knowledge back into the corporate, very much non-functional world. You can return to the barren moor of C# armed with Lispy methodology in a .NET environment.

There isn’t just one Lisp. There are lots and lots and lots of Lisps, and it’s hard for a newbie to decide between them. For now, we’ll introduce you to a friendly little hen called Chicken Scheme. It’s a language with round corners, a relaxed type system, and a focus on practical programming.

How practical? Chicken Scheme comes with both an interpreter (csi) and a compiler (csc). If you prefer one tool or the other, it’s perfectly fine to use just that. Or, you can test your code with csi and compile your finished projects with csc. But do try the interpreter at least once; it could change the way you program.

Installing Chicken Scheme is fairly easy. Macs use MacPorts.

sudo port install chicken

Linux uses the package manager of your choice.

sudo apt-get install chicken

.
Windows uses the chicken-iup installer.

It’s time to have some fun! Fire up the interpreter by opening a terminal and entering csi.

$ csi
CHICKEN
(c)2008-2011 The Chicken Team
(c)2000-2007 Felix L. Winkelmann
Version 4.7.0
#;1>

Chicken can add numbers.

> (+ 2 2)
4

Chicken can reverse lists.

> (reverse (list 1 2 3))
(3 2 1)

Chicken can test list elements for evenness.

> (map even? (list 1 2 3))
(#f #t #f)

Chicken can test list elements for <PROPERTY-OF-YOUR-CHOICE>.

> (map (lambda (element) (* element 2)) (list 1 2 3))
(2 4 6)

If you can learn to write lambdas, you’re well on your way to becoming a first-class functional programmer!

Starting to get the hang of it? Play around, don’t limit yourself to the code in a tutorial. It doesn’t take long to program something big and practical like a unit test framework (~ a day).

If you’re lost, login to Freenode IRC join the #chicken room. The folks there are friendly, competent, and hilarious. Finally, if you find Chicken Scheme isn’t doing what you want it to do, you can customize it. Sometimes all you need to be happy is a little ~/.csirc config file :)

MATLAB is horrid

matlab logoI wouldn’t even steal MATLAB, it’s that awful. The syntax is inconsistent, the GUI cumbersome, and the documentation next to useless. Hardly any of the examples are self-sufficient:

fnint

Examples

The statement diff(fnval(fnint(f),[a b])) provides the definite integral over the interval [a .. b] of the function described by f.

That’s not an example! Specify f, a, and b so that readers can understand how to call fnint. MATLAB’s documentation sucks!

In contrast, the newLISP manual is excellent. Here’s the documentation for the abs function.

abs

syntax: (abs num)

Returns the absolute value of the number in num.

(abs -3.5) → 3.5

Oh my God, it tells you how to call abs, it tells you what abs does, and it gives an explicit yet concise example of how to use it in real life. newLISP is free and its documentation is light years ahead of MATLAB’s. I blame it on corporate-style thinking; IBM’s articles are similarly dense/yet void of content.

I played with many different possible syntaxes for fnint and never found the right one. I tried defining a function fun in fun.m and calling integrate(fun, [0 2]). I tried using an anonymous function integrate(@(x) x + 1, [0 2]). I tried using a symbolic function integrate(‘x+1′, [0 2]). None of these worked. I tried using combinations of the above with the MATLAB fnint function. Still didn’t work. If you, dear reader, can elucidate the secret syntax for integrate and fnint, please comment.

Finally, my girlfriend and I came up with an integration function that not only works, it has decent syntax.

function y = riemann(f, xmin, xmax)
	delta = 0.0001;

	y = 0;

	for t=xmin:delta:xmax
		y = y + delta * f(t);
	end
end

fun = @(x) 5 * exp(1) ^ (-(x-3)^2);
riemann(fun, [0 2])

ans =
	0.6970

You still need to declare riemann in a file called riemann.m., and either evaluate the last two expressions fun … and riemann(fun… in the MATLAB interpreter or declare them before the riemann function in riemann.m.

And that’s a hassle. I’ll admit, even Erlang doesn’t let you declare functions in the interpreter, so I don’t expect MATLAB to let you. But it would be nice if the MATLAB interpreter language were a subset of the MATLAB script language and not a derivative.

The GUI

There’s no good reason to use a GUI interpreter. It just gets in the way. Except in the case of Windows, where the Command Prompt has pre-2000 conventions for copy and paste. I still would rather use the terminal.

matlab -nodesktop

You shouldn’t have to add a flag (a long one at that) just to keep the GUI from loading. And guess what? On Windows, the flag doesn’t do jack.

MATLAB exists to do integration of arbitrary functions, and it’s awful at it. There’s no reason to use this proprietary, non-free, dysfunctional language when perfectly decent alternatives exist.