Arc Forumnew | comments | leaders | submitlogin
Rudimentary pattern-matching in def
3 points by akkartik 4620 days ago | 5 comments
I just found a quick-n-dirty way to replace mac2 (http://arclanguage.org/item?id=17233) with pattern-matching support in def and mac:

https://github.com/akkartik/wart/commit/5e9d3fddb3#diff-2

Try it out:

  $ git clone http://github.com/akkartik/wart
  $ cd wart
  $ git checkout 5e9d3fddb3
  $ ./wart
  ready! type in an expression, then hit enter twice. ctrl-d exits.
  (def (foo n) nil)
  (def (foo 'a) 0)
  (foo 3)
  => nil
  (foo a)
  => 0
Prominent limitations:

a) No support for constants. (foo '0) ends up code generating to:

   ..
   if (0 = '0)
     ..
and so will always succeed.

b) Only supported in def without :case. I'm basically not sure whether to support selective quoting or pattern matching. Suggestions?



2 points by Pauan 4620 days ago | link

"Only supported in def without :case. I'm basically not sure whether to support selective quoting or pattern matching. Suggestions?"

Well, I don't see any problem with that, since everything pattern matching can do, :case can do, and vice versa. So it makes sense to me to define one in terms of the other. Whether you define :case as a pattern, or patterns as :case, will depend on which strategy you think is better.

Oh, I see, wart supports only a single :case, right? If it supported multiple :case's, then you could support pattern matching and :case, right?

-----

2 points by akkartik 4620 days ago | link

Yes, this isn't currently legal:

  def (foo) :case a :case b  # second case is ignored
Is this what you meant?

---

I think I wasn't clear about my meaning. Consider the following definition:

  def (foo 'a b)
    ..
This can mean two things:

a) Selective-quoting: foo takes two args, the first isn't eval'd.

b) Pattern-matching: that definition of foo is dispatched to if the first arg is a.

So I wasn't sure which to use. Since I posted this I ended up using backquotes for pattern matching, so for case b) you'd end up saying:

  def (foo `a b)
    ..

-----

1 point by rocketnia 4619 days ago | link

"Since I posted this I ended up using backquotes for pattern matching"

I agree with Pauan. This is reasonable. ^_^ Well, beware of corner cases like trying to match literal uses of the symbol 'unquote.

-----

1 point by akkartik 4619 days ago | link

Wart knows knows no symbol unquote, only a literal comma :)

-----

1 point by Pauan 4620 days ago | link

"Is this what you meant?"

Yes.

---

"Since I posted this I ended up using backquotes for pattern matching"

That sounds reasonable. It's what I would have done in the past.

-----