3 ms·
Pattern matching isn't just conditional matching. It's also binding, and even some common operations. Compare a naive Haskell map: map f [] = [] map f
by jarcane 11y ago
Pattern matching isn't just conditional matching. It's also binding, and even some common operations. Compare a naive Haskell map:
map f [] = []
map f (x:xs) = f x : map f xs
To a Racket one made without using (match...):
(define (map f lst)
(cond
[(empty? lst) '()]
[else (cons (f (car lst))
(map f (cdr lst)))]))
The former is far more terse, and also more directly resembles a definition of what map actually does. The latter is wordy, because all kinds of things have to be stated in explicit terms, and operations need to be performed manually instead of with simple destructuring binds.
This is a mild example too, it gets far, far more useful when you're dealing with type/struct fields and the like.
- abecedarius 11y agoThat wasn't quite a fair comparison. map f xs = if empty xs then [] else f (head xs) : map f (tail xs) (I like pattern matching too.)
- jarcane 11y agoThe point isn't to be a "fair" comparison, but rather to compare the number of explicit operations involved. I'd note that your Haskell example there is largely equivalent to the Scheme one.
- abecedarius 11y agoYes, it's equivalent on purpose. Yet in Haskell it's only a couple tokens longer than the pattern-matching original which you called "far more terse". To fairly test a claim, one should change only the variables the claim is about.
- jnbiche 11y agoJust curious why you would use that imperative example with Racket, and not an imperative language like Python, or even Haskell? You parenthetically mention (match) (ha!) but to someone who doesn't know the languages, give the impression that Racket can't do pattern matching. Anyway, this is the analogous `map` in racket: (define (my-map f lst) (match lst ['() '()] [(cons hd tl) (cons (f hd) (my-map f tl))])) It's a 1-to-1 correspondence, and is arguably the idiomatic way to define `map` in Racket.
- jarcane 11y agoI was largely using Racket as a common enough Scheme that I have installed my computer. I wanted an example from another functional language but in an older classical style (I was shooting for the Little Schemer here). I'm quite familiar with Racket's match, somewhere around my blog I even have a "proof" of sorts of using Racket's match to do the famous Haskell quicksort in just as few lines of code. If you really want an ugly rendition I could try and replicate one of the awful JavaScript versions of "map" that uses a for loop, but I thought that might obscure the comparison of operations too much, and the semantics wouldn't be equivalent (linked lists vs. JS arrays).