Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is much better handled in languages with pattern matching. And you can match on arbitrary fields.

Erlang:

  surf(Channels) ->
    lists:foreach(fun process/1, Channels).
  
  process(#channel{genre = "football"} = Channel) ->
    record(Channel);
  
  process(#channel{genre = "comedy", repeat = false} = Channel) ->
    record(Channel);
  
  process(#channel{genre = "crime", show_title = "Cops"}) ->
    skip;
  
  process(#channel{genre = "crime"} = Channel) ->
    record(Channel);
  
  process(_) ->
    skip.
Full gist: http://gist.github.com/250304


the problem with pattern matching is that its hard to dynamically change the dispatch table, in javascript I can just do

  dispatch_table[newthing].handler = function() .....


You can change the clause database in Prolog by asserta/assertz/retract, but that runs headfirst into the typical trade-offs involving mutable state, as does your Javascript example. Erlang also lets you change patterns by hot-loading code, but its design goes to great pains to do so with reasonable safety.

Also, pattern matching doesn't require all of the variables to be bound. A pattern may specify some values but just partially specify (a list with at least one remaining value) or constrain (any positive integer) others. This makes it vastly more flexible than just dispatching based on one value.


certainly, I am an erlang programmer and do love pattern matching, but as much as I pretend to hate javascript, I do love that modules/namespaces whatever are a first class citizen in a way they certainly arent with erlang, (they are at the vm level, but not so much the language, smerl is quite handy for that).

I should probably play with match specs more often


Which, if we were to take this example seriously, would be very important, since these rules would likely be user specified.


How should a function be "user" specified? (But which user?) The set of eligible options is well defined at the time of writing the program.


But the way they are composed, and where and when they apply, is most likely not!


A pattern matching solution is much more readable and it forces you to build small functions if you are pattern matching in the function declaration.


Right, AND being able to match on multiple fields and destructure them means that several awkward "which class owns the method" problems never arise in the first place.

(Multimethods are similar in many ways, though I find pattern matching far more useful.)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: