HNHacker News
TopNewBestAskShowJobs

tmhedberg

1,130 karma · joined March 15, 2011

submissionscomments
tmhedberg··on Little Lisp interpreter
Personally, my approach would be to change the association list so that the values, rather than being pairs of type `(Maybe (Parser String), String -> LispVal)`, are instead just values of type `Parser LispVal`, something like this:

    hashLiteralInfo =
        [ ('f', pure $ Bool False)
        , ('t', pure $ Bool True)
        , ('b', fmap (Number . toInteger . fromBase 2) (many $ oneOf "01"))
        -- ... and so on
        ]
The Boolean literal cases are then just parsers which consume no input and always return the same LispVal, instead of being separate, special cases that need to be handled by awkwardly passing a dummy string to a function which ignores its argument.
tmhedberg··on Impressions of Go
There are plenty of strongly, statically typed languages which do not have this problem because they have parametric polymorphism, i.e. generics.
tmhedberg··on Impressions of Go
A false dichotomy. You are correct that you can't outright prevent the writing of bad code in any language without crippling it; nonetheless, the design of a language can be contrived such that writing good code is the path of least resistance. It is not a binary choice between "safe but crippled" and "useful/flexible but unsafe". There is an entire continuum of choices to be made between the two extremes. The design of Go's error handling mechanism, while not the worst approach imaginable, unfortunately makes the programmer exert extra effort in order to do the "right thing".
tmhedberg··on Emacs is Dead (2010)
I think you have misinterpreted something. There have been a lot of Vim patches recently that are dramatically improving the long-existing Python scripting support in preparation for the upcoming Vim 7.4 release. But Bram has not said anything about "phasing out" VimScript. The two languages will continue to coexist (along with the handful of others that are also supported). There is far too much investment in VimScript, however flawed it may be, to actually deprecate or remove it.
tmhedberg··on Three Laws of Programming Language Design
Very true. Lisp's syntax is as much a component of its distinctive identity as its semantics. A language semantically identical to Scheme but without the homoiconic syntax falls far short of what Scheme is "about", despite what Doug Crockford might say.
tmhedberg··on Three Laws of Programming Language Design
Scheme (and FP in general) is much more than just first-class functions. If that's all that is required for a language to be considered functional, then nearly every modern programming language is a functional language, and the term becomes essentially meaningless. First-class functions are nothing special or unique anymore.

FP is also about frictionless composition of functions, declarative rather than imperative style, use of expressions instead of statements, and very critically, emphasis on statelessness and immutable data.

JavaScript is anything but stateless--it is extremely awkward, if not impossible, to avoid mutation in idiomatic JS code. Imperative statements abound, and everything is a reference, there are really no pure values to be found. Functions can be composed, but the syntax makes it unintuitive and ugly. And though it is probably not a hard requirement for FP, most FP languages at least make an attempt to distinguish pure functions from stateful procedures, e.g. via types in Haskell, or just naming conventions, as with Scheme's `set!`, but JS does not really facilitate this in any way.

Functions and lexical closures are undoubtedly some of "the Good Parts" of JavaScript, but these alone are not sufficient for functional programming. JS is fundamentally an imperative, OO language which happens to have a very light dusting of FP flavor on top.

tmhedberg··on The Shortest Crashing C Program
Why not:

    main=undefined
tmhedberg··on Haskell in Production: 12 Months Building ApiEngine
> Do those you mention handle content type and encodings correctly?

I honestly can't say for sure, but I've never encountered such a problem in my own usage. Maybe that just means I've been lucky. I just know from firsthand experience that they do a lot of things better than the HTTP package does.

> The main problem is the need to use "toValue" and "toHtml" all the time. I guess I don't understand why the element building functions don't accept strings.

First of all, if you're writing string literals and explicitly converting them with `toHtml`, you're missing out. Instead, enable the OverloadedStrings extension, and then you can do this sort of thing:

    html $ do
      head $ title "My Web Page"
      body $ do
        h1 "A Heading"
        h2 "A Subheading"
        hr
        p "A paragraph of text"
        p $ "Another paragraph, with an " <> (a ! href "http://example.com/") "embedded link"
        p $ em "Emphasized text" <> " and " <> strong "strongly emphasized text"
Notice the total lack of `toHtml` there.

The HTML DSL functions don't accept strings because String and Html are two fundamentally different types of data. Enabling the type system to differentiate between the two lets you do some pretty nifty things. For instance, if you were to write

    "<script>alert('XSS!');</script>" :: String
you'd be in trouble, but you can't do that since blaze-html doesn't accept plain old strings. Instead, you'd write

    "<script>alert('XSS!');</script>" :: Html
Note how only the type is changed, but now, the string will be transparently converted to "&lt;script&gt;alert('XSS!');&lt;/script&gt;" before it's added to the document, and thus you're safe, without having to actually do anything different. The type signatures I gave are superfluous of course, since they'd be inferred automatically. The type system makes this kind of flaw impossible.

Plus, since blaze combinators are just Haskell, and the Html type is a monad, you can use all the usual Monad functions with Html:

    ol $ mapM_ (li . toHtml) ['A'..'Z']
That generates a 26-item list of letters from A to Z. Yes, you do have to do the explicit conversion to Html there, but I think that's a small price to pay for all the flexibility afforded by templating HTML with full-fledged Haskell code.

> But for templating, I just don't like embedding templates in the actual source code of the HTTP verb it's for. The main controller code should be about preparing data for the UI, and the UI should be separate from the controller code. You could put it in a separate file and function and import it, of course, but it's still Haskell code, which must be compiled along with the entire app, which slows down the development cycle a lot.

Yeah, I just put "view code" like the above examples into a separate module and import it. I don't find the slowdown to be significant, but maybe that's just me. In any case, true template languages have to be compiled too, either with the rest of the program or at runtime, so one way or another you incur that cost no matter what you're using.

> I haven't looked closely at the various web frameworks to see if they support Rails-style reloading (ie., recompiling and reloading the app on each page load). Do you know?

Yesod does this by default, and Snap can, if you use `snap-loader-dynamic` for your development builds. I believe they both use the awesome `hint` package for runtime eval and compilation of Haskell code. I don't think Happstack has any auto-reloading capability though.

> Why invent something that looks like HTML but isn't? HAML syntax is basically (almost) CSS selectors, that's the whole point. And again, it's apparently meant to be placed inline.

It doesn't seem that different from HAML to me, but it's clearly a subjective judgment. :) And it doesn't have to be inline. It uses the QuasiQuotes language extension, which means you can do inline snippets or write it in a separate file, however you like.

Hamlet, Cassius, Lucius, and Julius (collectively, the "Shakespearean" template languages) are developed by the Yesod framework guys, not Snap, by the way. Snap uses a template language called Heist by default, which I don't particularly care for (I just use blaze-html instead).

> Oh, interesting. I don't know about MonadIO yet. Will definitely read up on this.

If you use liftIO, you're using MonadIO. That's what liftIO does, it's an adapter between plain IO values and polymorphic MonadIO values. But if library authors use MonadIO instead of IO, you can omit the explicit conversion. This isn't something you really have control over as the user of a library though.

> With more complex libraries, the machine-generated docs become increasingly obtuse. For example, I would never, ever have figured out how to use HXT with Hackage alone. I mean, look at it!

Fully agreed. HXT is a huge, complex beast! I don't think it's fair to judge all libraries by that standard, though. HXT is clearly at an extreme end of that continuum.

tmhedberg··on Haskell in Production: 12 Months Building ApiEngine
Just a few thoughts on the points you made:

> * The HTTP library (Network.HTTP) is not encoding-aware. It ignores Content-Type and returns a String with some undefined encoding. So if you grab a resource which is, say, ISO-8859-1, anything that works with UTF-8 will potentially blow up.

Agreed that the HTTP package is rough around the edges. It also doesn't support HTTPS, which seems like a major shortcoming to me. Fortunately, there are several better-designed alternatives (which have the added benefit of being more efficient), e.g. http-streams and http-conduit.

> * The string libraries are confusing. There is String, but also Text. Both are supposed to be Unicode-aware, but many of the operations you want are in Text, requiring conversions back and forth.

This pain can be mitigated somewhat by using `{-# LANGUAGE OverloadedStrings #-}`, at least when you're working with literal Strings, ByteStrings, and/or Texts. The main problem with the proliferation of string types is when using multiple libraries, each of which expect a different type of string (or one expects a strict ByteString and the other a lazy ByteString). Then the conversions can get irritating.

Generally speaking, you should use Text for textual strings, ByteString for binary data, and String in simple cases when the convenience of using Prelude or list functions trumps performance concerns. They all have reasonably well defined uses.

> * There are multiple libs for HTML/XML parsing, and no clear winner. HaXml was buggy and did not parse my HTML correctly. TagSoup and HandsomeSoup had weird APIs I did not like. I ended up with HXT, which uses Haskell arrow syntax extensively and is therefore incomprehensible, even when I understand what and how it does it. It feels a lot like people who write ambitious libs in Ruby with too much "magic". Haskell is a functional language and should be wonderful for parsing HTML/XML using XPath or CSS selectors, but it's a nightmare. HXT's parser is impure by default (!) and you have to google some tutorials to find out how to use its pure version, which the tutorial writers (in the same breath) dissuade you from using.

Have you tried the `xml` package [1]? It's not as sophisticated as something like HXT, but for a lot of uses, it does the trick and is far easier to work with. HXT is intimidating for sure, but apparently very powerful once you learn it (I haven't bothered).

> * For the frontend I ended up using Happstack Lite because it's small and about as easy to get started with as Sinatra. Unfortunately, the first templating system it recommends, Blaze, is crap. With Blaze you write the template inline, building an XML tree, similar to Ruby's "Builder" gem, but the syntax is ugly and unnecessarily complicated. The other recommended templating systems, HSP and Hamlet, are like ERB or PHP, so a serious step backwards from HAML. In the end, I could not find anything like HAML.

Funny, I personally think blaze-html is terrific. I like having a Haskell EDSL for HTML generation instead of having to drop into a specialized and restricted "templating language" for that purpose.

If you want something like HAML, check out `hamlet` [2]. It's directly inspired by HAML and is the main templating engine of the Yesod web framework.

I found Snap to be somewhat easier to work with than Happstack, after trying them both. It occupies about the same level of abstraction. Yesod is a more full-stack Rails-like framework, which some people prefer. You can pretty easily mix and match components of the different frameworks however you like; they are nice and modular. I often use snap-core, acid-state, digestive-functors, and blaze-html together for simple web apps, even though they are not all part of any one framework.

> * I haven't delved very deeply into Happstack yet, but like many Haskell libs it seems to make simple things more complicated than they ought to be (eg., the routing system). One annoyance I remember is the fact that HTTP verbs aren't IO, which makes code less intuitive, since obviously in a modern web app, HTTP verbs are going to be doing IO (things like talking to databases), and so you have to use liftIO a lot.

Frequently having to use `liftIO` is a sign that the library author overspecialized their functions to IO. If more people would write libraries using `MonadIO m => m a` instead of `IO a` that problem would basically disappear. Polymorphism is wonderful, when you are able to apply it.

> * Perhaps the biggest issue for me was the general lack of high-quality documentation (Happstack itself has almost none). Sure, there are tons of searchable machine-generated docs, which is great, but that documentation lacks the bits that tie everything together. Since Haskell is mainly about applying functions to values of types, it is very decentralized; knowing what function to use is only part of the game. It's just as important to know how its return value plays with the rest of the function space, because so much of Haskell revolves around composing functions in idiomatic ways. This is very different from, say, Ruby, where you know a method returns an object, and an object only has the methods its class provides; this centralizes, clusters and constrains the information into easily digestible pieces.

I don't disagree that more documentation is a good thing, and some libraries are under-documented. But I can also point to examples of Haskell libraries with superior documentation to nearly anything else I've encountered. Some authors really go the extra mile; it's great.

My experience has been that the type system plus Haddock docs are frequently enough for me to figure out a library even without any prose documentation at all. This, to me, is a huge advantage of Haskell. The types only fit together one way, and that way is the correct one. When using a library with well-designed types, you basically can't get it wrong.

I certainly understand why this would not be so easy for a newbie. It gets much, much easier with experience, though.

[1] http://hackage.haskell.org/package/xml [2] http://hackage.haskell.org/package/hamlet

tmhedberg··on Plans for Vim 7.4
New features are voted on not by mailing list/Google group participants but by users who have donated at least €10 to the Ugandan charity that Bram sponsors via Vim development.

Also, I'm not sure in what sense mouse integration is "the obvious flaw", given that (A) it already exists if you use the GUI version, or in the terminal if your terminal supports mouse reporting (see :help mouse-using) and (B) most Vim users tend to actively avoid the mouse anyway.

tmhedberg··on New GitHub Logo
From the official Git README:

    "git" can mean anything, depending on your mood.

     - random three-letter combination that is pronounceable, and not
       actually used by any common UNIX command. The fact that it is a
       mispronunciation of "get" may or may not be relevant.
     - stupid. contemptible and despicable. simple. Take your pick from the
       dictionary of slang.
     - "global information tracker": you're in a good mood, and it actually
       works for you. Angels sing, and a light suddenly fills the room.
     - "goddamn idiotic truckload of sh*t": when it breaks
https://github.com/git/git/blob/master/README
tmhedberg··on Designing a modern email
Nearly all marketing messages that I receive are HTML only, not multipart. In fact, this is a problem that seems almost as if it is specific to marketing spam; ordinary people who send HTML mail seem to use MUAs that sensibly send a plain text part as well. But whatever tools marketers use to send their "newsletters" seem to be ignorant of best practices, or they just don't care about the small market segment of people who don't read HTML mail.

This is not a complaint. I don't care to read what they're sending me anyway, and the wall of visual garbage that greets me when I open one of those messages has trained me to reflexively hit delete and move on.

tmhedberg··on Setting up Sublime Text 2
> Until Git can ignore trailing spaces as part of the merge strategy

It can:

    git merge -X ignore-space-at-eol
tmhedberg··on List out of Lambda
> Not everyone is used to read that math notation.

Agreed, but it doesn't take more than a couple of sentences to describe the entire syntax of the λ-calculus. It's not hard to pick it up even if you've never encountered it before.

Contrast that with JavaScript, where even as someone who has written my fair share of it, my eyes tend to glaze over when they hit a string of `});}))());};`. Yet people happily write that sort of thing, then turn around and complain about nested parentheses in Lisp!

tmhedberg··on List out of Lambda
Agreed. I can't understand how something like

    function(x) {return function(f) {return f(x);};}
can be considered easier to comprehend than

    λx. λf. f x
tmhedberg··on Zsh-lovers – tips, tricks and examples for the Z shell
> (like one thing that comes to mind is recursive globbing with two astersisks, but to be honest I have no clue if maybe bash can do that too by now)

It can, if you set the `globstar` option:

    $ shopt -s globstar
    $ echo **/*.txt
    a/a2/baz.txt a/bar.txt a/foo.txt b/bar.txt b/foo.txt
tmhedberg··on Mars trip to use astronaut poo as radiation shield
Exposure to radiation does not make it radioactive.
tmhedberg··on How I learned to love rebase
Automatic garbage collection won't destroy any unreachable objects less than 2 weeks old. This is the default time window; you can override it via the `gc.pruneexpire` config option.

Given this grace period, disabling AGC altogether is probably overkill, but there is nothing wrong with that, if it's really what you prefer.

tmhedberg··on Why I can’t work at Google
I've interviewed at Google NY, and though I do seem to recall being asked if I knew anyone that worked there, I never got the impression that my answer influenced the outcome of the interview process. It was just a friendly, casual question asked as a way to break the ice.
tmhedberg··on Language War - Scala versus Python
Nowhere in his post did tikhonj suggest that compilation == correctness, even in Haskell. Of course it isn't. The only people making that assumption are wyqueshocec's coworkers, and naturally they're getting burned as a result.

The key point is that a sufficiently expressive type system gets you far closer to correctness on the basis of type checking alone than does a weaker static system like Java's or a dynamic one like JS's. You should still write tests, you just won't have to write as many in order to reach the same degree of confidence in your code.

tmhedberg··on Language War - Scala versus Python
Not all static type systems are created equal. The sort of type checking provided by Java (and similar languages) provides far less safety than that of a full-fledged type-inferring language like Scala or Haskell.

I use Ruby and JavaScript professionally. I do like Ruby for a number of reasons, and JavaScript I can at least live with. But in both languages, I constantly find myself spending tons of time tracking down bugs that would have been discovered right away if I had Haskell's type system at my disposal.

tmhedberg··on Abandoning bottom-posting
It is only one data point among many, I admit, and it would be unfair to characterize someone's expertise based solely on their choice of email quoting style. But in my (completely anecdotal) experience, there is more often than not a correlation between the two. Maybe it's just the email discussion lists that I frequent, where bottom posting tends to be the norm, and top-posted messages mostly come from people who could have answered their own question had they bothered to spend 30 seconds on Google before going to the mailing list.
tmhedberg··on Abandoning bottom-posting
I agree that inline replies, when taken to the extreme that you illustrate, are more asinine than they are useful. Personally, I tend to reply to a paragraph or two at a time, a style which doesn't, in my opinion, have the same "you idiot" rhetorical feel. It's just easier to read and understand than a giant block of text responding to several unrelated points, followed by a giant untrimmed quote. Not all bottom posting/inline quoting is of the holier-than-thou nature. :)
tmhedberg··on Abandoning bottom-posting
Bottom-posting, due to its falling out of favor in the mainstream, has become a shibboleth that signifies a certain degree of competence with technology and Internet communication in general. While I'd certainly prefer it if everyone I corresponded with followed proper quoting etiquette, I have to say that it's also fairly convenient to glance at an email message and immediately be able to infer with reasonable confidence what level of expertise to expect from the stranger on the other end (at least in the context of public technical discussions).

Meanwhile, I'll keep trimming quotes and bottom-posting, whether or not anyone else is doing it. It just makes sense, damn it. I know it's a losing battle, and I don't care.

See also: users/MUAs that send HTML only instead of multipart/alternative or just plain text. I read mail with Mutt, and when I open a message and see nothing but angle-bracketed noise, it's almost guaranteed to be an unwanted marketing message or solicitation from some online service I've signed up for in the past. The visual garbage makes it easy to just tab to the next message in a split second without a thought. On the rare occasion that it's something that I actually care to read, I can pipe it through Pandoc to render it legible with a couple of keystrokes.

tmhedberg··on Haskell I/O is pure
Sorry, but I disagree. A Haskell program emphatically does not have any concept of impurity or statefulness whatsoever, except in the form of `unsafePerformIO`, which circumvents the type system, only comes into play under "extenuating circumstances", and which an ordinary program has no use or need for.

The language itself does not have any notion of sequencing or order of evaluation, nor does it need one. It inhabits a pure, mathematical universe where such things have no meaning. Given an arithmetic expression such as

    (1 + 2) * (3 - 4)
it naturally makes no difference which parenthesized expression is evaluated first, because the evaluation of mathematical expressions cannot have side effects. It would be absurd to consider a universe in which such a choice could influence the result of fully evaluating the expression, because such a universe would be wholly unlike our own, to the extent that our intuitive rules of logic and causality would no longer apply.

Likewise, given the Haskell expression

    putStrLn "Hello" >> putStrLn "world!"
it makes no difference which of the two IO expressions is evaluated first, because the evaluation of those values cannot have side effects. The second one may be evaluated before the first; it makes no difference. The execution of the resulting action will have side effects and impose sequencing, but there is no way to express execution or cause it to occur in the Haskell language. Execution can only happen "outside" of the context of the program itself, not in the program's abstract and pure universe, but in our own imperative and stateful one, as a side effect of the RTS.

A C program, to extend the metaphor, knocks over each domino one by one as soon as it is placed. In fact, placing the domino and knocking it over are one and the same thing. The programmer has no opportunity to leave the room before the side effects come into play, because imperative languages do not distinguish between evaluation and execution. A purely functional language not only draws that distinction, but eliminates execution from the picture entirely, leaving it to some external entity to actually do the deed that the program constructs from pure components.

tmhedberg··on Haskell I/O is pure
It can be. A value of type `IO foo` is an ordinary, pure value just like a value of any other data type. It can be passed as an argument to a pure function, returned from a pure function, manipulated using any functions that can apply to `IO` values, stored inside an arbitrary data structure, composed with other `IO` values to make new ones, etc.

What isn't pure is the process of extracting the `foo` from the `IO foo`, i.e. getting the result of the I/O action. For instance,

    getLine :: IO String
is not a function in Haskell, which you can "call" in order to get a string from stdin. It is instead a value which represents an I/O operation yet to be performed. There is no way to force it to yield its result within your entirely pure program (ignoring escape hatches like `unsafePerformIO` and friends), but you can nonetheless compose it with other I/O operations which depend on its result, such as putStrLn:

    echo :: IO ()
    echo = getLine >>= putStrLn
The above defines a pure value representing an I/O operation which, when performed, will echo a line from stdin to stdout. The `>>=` combines the two pure values to yield a new pure value. Again, there is no way to directly cause this I/O action to be executed, which would necessarily introduce impurity. You can only ensure that it will happen later by threading it into the special I/O operation `Main.main :: IO ()`, which every program must define, and which will be implicitly performed when your program is run.

By reifying "statements with side effects" into simple, pure, first-class values of type `IO`, Haskell lets us remain 100% pure even while our program will eventually have effects on the real world outside of the machine. Haskell code is just a set of pure declarations; the side effects are deferred until after our code has already run (which conceptually happens instantaneously when the program is launched). Since our code runs "before" any side effects occur, it cannot possibly depend on their results.

A Haskell program merely sets up the dominoes in an elaborate arrangement, then looks the other way while the runtime system knocks over the first one.

tmhedberg··on [dead]

    git filter-branch --index-filter 'git rm --cached --ignore-unmatch rsa_private_key' -- --all
Now you have a completely rewritten repository. Anyone who cloned or forked your repo will have the old history, divergent with your own, still containing the sensitive key. It's quite a mess to clean up, but that's about all you can do.
tmhedberg··on Why type systems are interesting (2004)
> You can do this with any functor.

Not to be pedantic, but being a functor has little to do with the fact that you can add and remove elements from lists.

Knowing that a particular type is an instance of `Functor` tells you only one thing about that type: that you can `fmap` functions over its contents. But look at `fmap`'s type:

    fmap :: Functor f => (a -> b) -> f a -> f b
There is no function with that type which can extract values from a functor, nor insert new ones. `fmap` can only modify the values already contained by the functor, leaving them in the container.

Extraction of contained values from a wrapper and lifting/insertion of values into a wrapper require pattern matching and constructor application respectively, which means the type must have exposed constructors, a property independent of whether that type is a functor.

tmhedberg··on Linus on kernel changes breaking user programs (from 2012/12/23)
As far as I know, the "ENT" in ENOENT refers specifically to a "dentry" (directory entry), i.e. the kernel data structure `struct dentry`, identified by a pathname in the virtual file system. It's not supposed to be a generic term for an entry in some arbitrary container of data.

I do see where you're coming from now, but I still think any usage other than the standard "no such file" meaning is errno abuse.

tmhedberg··on Linus on kernel changes breaking user programs (from 2012/12/23)
What if an ioctl is trying to indicate that a certain "entry" is not valid or available?

I don't understand the question. It is not possible for ioctl to be called on a valid, open file descriptor that represents a file that is not valid or available. Even if the file is unlinked after being opened, the kernel will ensure that it remains available to any processes that have it open until they close the file descriptor.

Like when it is returning a cached entry or dealing with some container, where a notion of an entry does make sense.

I honestly don't know what you mean by this. ioctls, like nearly all Unix system calls, are file system operations, they necessarily and by definition refer to files.

Insisting that ENOENT is reserved for path operations seems asinine.

On the contrary, ENOENT has meant "No such file or directory" since the early days of Unix history. Arbitrarily deciding to redefine it now would be asinine. There are other errno values to represent other error conditions.

← PreviousPage 2 of 6Next →