News for hackers. Stuff that matters.
Re:What else are we getting wrong about programming languages? by raiph on Tuesday November 01, 2016 @12:48AM (#12843498)
The Perl 6 student begins:

    sub add(\number1, \number2) { number1 + number2 }
If you call `add` with simple numbers it works:

    say add(1, 2) # 3
Other types of number too:

    say add(0.1, 0.2) == 0.3 # True
It works even for newbie definitions of "number":

    say add('0.1', '0.2') == '0.3' # True
A sufficiently determined newbie can of course break `add`:

    say add('foo', 'bar') == 'waldo'
The program stops with a suitable error message ("Cannot convert string to number ...").

----

The student moves on to a more advanced course...

----

Type annotations are introduced:

    sub add(Numeric \number1,
            Numeric \number2) { number1 + number2 }
Everything still works as expected:

    say add(1, 2) # 3
But we get better error checking:

    say add('foo', 'bar') == 'waldo'
This generates a compile-time type-checking error ("Calling add(Str, Str) will never work with declared signature (Numeric \int1, Numeric \int2)").

So, reason 1 for using types: get type-checking that catches errors at compile-time.

You can use native types for closer-to-the-metal speed (compact representations, no automatic overflow checking, etc.):

    sub add(num64 \number1,
            num64 \number2) { number1 + number2 }
`num64` corresponds to C's double float datatype representation. This sub will likely outperform the versions of `add` that do not have natively typed parameters.

A third reason for explicit types is to take advantage of C interop:

    use NativeCall;
    sub add(int32, int32) returns int32 is native("calculator") { * }
If you've got a local C library (called "libcalculator.so" or somesuch) then this:

    say add(1,2)
will call the function with the symbol name `add` in that library.

And so on.

There are no comments on this comment yet.