"retard" <[email protected]> wrote in message news:[email protected]... > Tue, 09 Mar 2010 13:52:52 -0500, Nick Sabalausky wrote: > >> "BCS" <[email protected]> wrote in message >> news:[email protected]... >>> Hello retard, >>> >>>> Really? I'd really like to see how this is done. Especially the nested >>>> matching of algebraic constructs, e.g. >>>> >>>> my_list match { >>>> case 1 :: 2 :: 3 :: tail => 123 :: tail } >>>> in D: >>>> >>>> if (list.getElemAt(0) == 1 && >>>> list.getElemAt(1) == 2 && >>>> list.getElemAt(2) == 3) { >>>> return list.new(123).append(list.range(3, list.length)); } >>> >>> >>> I'd rather the following over either: >>> >>> if(list[0..3] == [1,2,3]) return new list(123, list[3..$]); >>> >>> >> Expanding on that: >> >> if(list[0..3] == [1,2,3]) return new list(123, list[3..$]); >> if(list[2..4] == [10,11,12]) return new list(list[0..2], 200, >> list[4..$]); if(list[0..2] == [9,8]) return new list(100, >> list[3..$]); // Omit list[3] >> return list; >> >> Hmm. I'd rather something closer to this (purely hypothetical syntax, of >> course): >> >> return match(list) >> { >> case [1,2,3]~tail: 123~tail; >> case [a,b,10,11,12]~tail: [a,b]~200~tail; case [9,8]~tail: >> 100~tail[1..$]; default: list; >> } > > Your examples more or less suggest that you haven't used lists much. The > reason why list pattern matching usually works the way I showed is that > it's a simple linked list with a unbound payload type. Some typical use > cases are: > - find out whether the list is nil > - return the head and tail > - return n first elements and the tail > > Everything else costs a lot. The syntax encourages the thinking that > extracting values is rather expensive and you shouldn't re-evaluate them. > Indexing is O(n). > > You also very very very rarely jump over elements on the list. > > Lists can also be infinite in lazy languages so [1..$] makes little > sense. So the example was a bit misleading. But if you see how lists are > implemented with algebraic types, you might also see how other structures > like trees (list is a degenerated tree) are matched.
Well, I wasn't really thinking about lists specifically. I realize I wasn't clear on that, and probably should have renamed it "array" or something. I was just thinking about a much more general pattern matching construct, not just linked lists. Also, Andrei's pointed out in the past (convincingly, IMO) that a heavily list/head-and-tail type of thinking can lead to incorrect and suboptimal implementations (ie, the quicksort example). But, regardless of any of that, like I said, it was just hypothetical sample syntax. No more than a minute or two of thought put into it (hell, I can think of other problems with it right now). In fact, I was mainly just using it to point out that there's room for something much better than BCS's example.
