On type functions
Jacob Carlborg
doob at me.com
Mon May 4 12:37:26 UTC 2020
On Sunday, 3 May 2020 at 09:35:34 UTC, Stefan Koch wrote:
> The type function is born. (I thought I came up with it, but
> recently remembered that I first saw it in idris
> (https://www.idris-lang.org/))
It actually exists in several other languages:
* Zig
* Ruby
* Objective-C (kind of)
In Ruby, everything is an object, including classes. Since also
primitive types are objects it natural falls out that Ruby have
first class types.
class Foo
end
class Bar
end
a = Foo.new # usually how one creates a new instance
puts a.class.name # prints "Foo"
ARGV[0] = 'bar' # ARGV is the parameters passed to the script
cls = ARGV[0] == 'bar' ? Bar : Foo
b = cls.new
puts b.class.name # prints "Bar"
> D already have a way of expressing a "type variable" the
> `alias` keyword.
> so having a function such as
>
> bool isInt(alias T)
> {
> return is(T == int);
> }
>
> as a completely natural thing to write.
My biggest issue with this has not been performance but instead
the one needs to write the code in a completely different style
(recursive templates and there are many corner cases). I think
it's important that the existing algorithms (std.algorithm) works
with types. Looking at the example in one of the other posts in
this thread [1]:
alias[] map(alias f, alias[] a) {
alias[] r;
foreach (e; a)
r ~= f!e; // can we?
return r;
}
enum isType(alias a) = is(a);
static assert([map!(isType, AliasSeq!(1, int, "meh"))] == [false,
true, false]);
I think it would be very unfortunate if the existing algorithms
didn't work and they need to be recreated. Then we're back to
what we have today, like `staticMap` and `Filter`, (perhaps just
with a different implementation).
I want full support for first class types. Not just limited to
some specific functions. This should be able to work:
import std.algorithm;
import std.array;
static assert([int, char, long].map!(a => a.stringof).array ==
["int", "char", "long"]);
But I guess "type functions" are better than nothing.
[1]
https://forum.dlang.org/post/jaobevgsoxqibieuayih@forum.dlang.org
--
/Jacob Carlborg
More information about the Digitalmars-d
mailing list