A More Readable Type Lambda Trick

Posted on Mar 31, 2012 (2 years ago). Seen 4,386 times. 2 comments. Permalink Feed
Member since Nov 1, 2011
Location: Oakland
Stream Posts: 2
Tagged as: Scala Tutorial

So you've got some type that takes multiple type parameters, like:

Code:
trait State[S, A]

... and you've got some code that needs to fix one of the type parameters while letting the other(s) vary. We usually use the "type lambda trick" to partially apply type arguments, like this:

Code:
def stateMonad[S] = new Monad[({type L[A] = State[S, A]})#L] { ... }

Sometimes you see this written with actual Greek characters using Unicode, where "L" is written as a lower case lambda, hence the name. Using Greek letters in source code is for jerks, unless you happen to actually be Greek, in which case go for it. However, even with the Latin "L" I don't find this style of code particularly readable, when some type lambda needs to be given a name and referenced more than once. So I propose the following new convention:

Code:
def stateMonad[S] = {
type `State[S]`[A] = State[S, A]
new Monad[`State[S]`] { ... }
}

The backticks permit use of the special [] characters which wouldn't otherwise be allowed in an identifier. At any rate, the idea is to mimic the appearance of multiple type parameter lists without yet having them in the Scala language.

Comments

Posted on Mar 31, 2012
Photo Dan Rosen
Member since Nov 1, 2011
Location: Oakland
Update: some interesting discussion over on Rahul's gist
Posted on Apr 1, 2012
Photo Jed Wesley-Smith
Atlassian
Member since Apr 1, 2012
Using Greek letters in source code is for jerks, unless you happen to actually be Greek, in which case go for it


Fairly strong, and a bit silly for type lambdas, where you never need to refer to any of the symbols outside the expression, so there is no usage requirement on anyone apart from the original author. Also, greek letters often have well established meanings from the field of mathematics – and while often unintelligible most mathematicians are usually not jerks.