Hacker News new | ask | show | jobs
by sgrove 2660 days ago
I haven't heard the term "multiple function heads" - is it similar to Haskell's way of defining functions? e.g.

    fib 0 = 0
    fib 1 = 1
    fib n = fib (n-1) + fib (n-2)
2 comments

Yeah, this is Erlang:

    fib(0) -> 0;
    fib(1) -> 1;
    fib(N) -> fib(N-1) + fib(N-2).
But these are all compiled into, essentially, a giant case statement. It’s a syntactic sugar. Your last line is missing a dot at the end.
Concise code is its own reward. Yes, it's syntactic sugar, but there's a reason syntactic sugar is valuable.

Even if performance is the same, you wouldn't prefer this Javaesque code:

    Int.from(8).multiply(5)
You'd use `8 x 5` were it available.

Several discrete function heads are easier to mentally parse than a long case statement because you know without a shadow of a doubt that there's no code in the function above or below the case statement, and you always have all relevant bindings directly adjacent to their usage.

Consider this Erlang code:

    f(X, Y) ->
       case X of
          {1, 2} ->
              low;
          {2, 4} ->
              high;
          {3, 6} ->
              Y
       end
    end.
When you get to the 3rd case statement and `Y` appears, it's jarring because it was declared several lines removed.

Instead, this code makes it explicit for each function clause that we don't care about the 2nd argument, and when we do care, it's immediately obvious where it came from.

    f({1, 2}, _) ->
       low;
    f({2, 4}, _) ->
       high;
    f({3, 6}, Y) ->
       Y.
Yes, I agree with your point, I've written plenty of Erlang.
Exactly. I don’t know what the typical industry term for it might be.
Multiple Dispatch / Multimethods (I think?)
Interesting, it appears that multiple dispatch is accurate. Thanks.
Pattern matching!
No, it relies on that, but the creation of multiple function clauses via different matched heads itself isn't simply pattern matching.