Null references redux
language_fan
foo at bar.com.invalid
Mon Sep 28 18:26:09 PDT 2009
Mon, 28 Sep 2009 20:17:54 -0400, Nick Sabalausky thusly wrote:
> "language_fan" <foo at bar.com.invalid> wrote in message
> news:h9relp$1ebg$4 at digitalmars.com...
>> Mon, 28 Sep 2009 22:33:26 +0000, language_fan thusly wrote:
>>
>>> Value types can be incorrectly initialized and nobody notices. E.g.
>>>
>>> int min;
>>>
>>> foreach(int value; list)
>>> if (value < min) min = value;
>>
>>> Now I can tell you, in functional languages there is no other way. All
>>> initializations have to be correct, they are final, they are constants
>>> and they can be initialized incorrectly. But there are some tools that
>>> help in this. Functions can be automatically tested. Invariants, pre-
>>> and post-conditions can be set. Still, I can even bet they are much
>>> safer than D in every possible way. How is this possible?
>>
>> For instance if I use the example given above, I write it like this in
>> a functional language:
>>
>> find_min:: Ord a => [a] -> Maybe a
>> find_min [] = Nothing
>> find_min (h:t) = Just $ foldl min h t
>>
>> You can then use quickcheck to verify the result in some fancy way.
>>
>> I just cannot think of any way how you could crash programs written in
>> this way. They are solid as a rock.
>
> I'm not particulary accustomed to that sort of syntax. Am I correct in
> my analysis that that essentially does something like this?:
>
> // Assuming that:
> // 1. Variables of type void could be declared and had value 'void'. //
> 2. 'any(T,U,V)' was a "supertype" that can and must be one (and only
> one) of T, U, or V.
>
> immutable any(int,void) min(immutable any(int,void) a, immutable
> any(int,void) b)
> {
> static if( is(typeof(a) == void) && is(typeof(b) == void) )
> return void;
> else static if( is(typeof(a) == int) && is(typeof(b) == void) )
> return a;
> else static if( is(typeof(a) == void) && is(typeof(b) == int) )
> return b;
> else
> return a<b? a : b;
> }
>
> immutable any(int,void) findMin(immutable int[] list) {
> static if(list.length == 0)
> return void;
> else
> return reduce!("min(a,b)")(list); // 'reduce' from phobos2
> }
Well to be honest, I thought I knew how to read D, but this is starting
to look a bit scary. It looks like it does almost the same. I just used
lists instead of arrays since they are the basic data type in functional
code. Second, the find_min accepted any type that implements the 'Ord'
class, i.e. supports the '<' relation, not only ints. I guess it could
be solved by changing some pieces of code to look like this:
> immutable any(T,void) findMin(T)(immutable T[] list) {
My original idea was to just show that it is much harder to make similar
kinds of errors with algebraic data types. I should have made a less
generic :-)
More information about the Digitalmars-d
mailing list