Is D a cult?

retard re at tard.com.invalid
Tue Mar 9 12:45:13 PST 2010


Tue, 09 Mar 2010 13:52:52 -0500, Nick Sabalausky wrote:

> "BCS" <none at anon.com> wrote in message
> news:a6268ff10f2a8cc8c1b9f4d1252 at news.digitalmars.com...
>> 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.



More information about the Digitalmars-d mailing list